gpt4 book ai didi

c# - 如何在返回对象的 C# 中使用 ASP.NET Web API

转载 作者:太空宇宙 更新时间:2023-11-03 23:41:41 24 4
gpt4 key购买 nike

我有一个要求,我从 Web API 方法返回一个对象,我想做的是在我的 C# 代码中使用返回的对象,如下所示:

网络 API 方法:

public Product PostProduct(Product item)
{
item = repository.Add(item);
var response = Request.CreateResponse<Product>(HttpStatusCode.Created, item);

string uri = Url.Link("DefaultApi", new { id = item.Id });
response.Headers.Location = new Uri(uri);

return item;
}

使用 API 的 C# 代码:

Public Product AddProduct()
{
Product gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };

//
//TODO: API Call to POstProduct method and return the response.
//

}

对此有什么建议吗?

我有一个实现,但它返回一个 HttpResponseMessage,但我想返回对象,而不是 HttpResponseMessage。

public HttpResponseMessage PostProduct(Product item)
{
item = repository.Add(item);
var response = Request.CreateResponse<Product>(HttpStatusCode.Created, item);

string uri = Url.Link("DefaultApi", new { id = item.Id });
response.Headers.Location = new Uri(uri);

return response;
}

使用 API 的代码:

using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:9000/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };

HttpResponseMessage response = await client.PostAsJsonAsync("api/products", gizmo);

var data = response.Content;

if (response.IsSuccessStatusCode)
{
// Get the URI of the created resource.
Uri gizmoUrl = response.Headers.Location;
}
}

这里是代码段:

HttpResponseMessage response = await client.PostAsJsonAsync("api/products", gizmo);

返回 HttpResponseMessage 但我不想要这个,我想返回 Product 对象。

最佳答案

尝试:

if (response.IsSuccessStatusCode)
{
// Get the URI of the created resource.
Uri gizmoUrl = response.Headers.Location;

var postedProduct = await response.Content.ReadAsAsync<Product>();
}

关于c# - 如何在返回对象的 C# 中使用 ASP.NET Web API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28850983/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com