我有一个要求,即从 Web API 方法返回一个对象,我想要做的是在我的 C# 代码中使用返回的对象,如下所示:
WEB 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/