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

时间:2015-03-04 09:36:51

标签: c# asp.net-mvc asp.net-web-api

我有一个要求,我从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对象。

1 个答案:

答案 0 :(得分:2)

尝试:

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

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