Skip to main content
 首页 » 编程设计

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

2024年08月06日36mate10pro

我有一个要求,我从 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>(); 
}