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

标签 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 对象。

最佳答案

尝试:

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/

相关文章:

c# - 单击该特定用户的按钮更改连接字符串

c# - UWP 中的 ListView

c# - 如果单词比 X 长,则用点替换字符串的结尾

c# - MVC 两个 Controller 一个 View

c# - MVC5 Controller 参数中的重音

c# - .net web api 服务器中的静态变量

asp.net-web-api - Hangfire、Autofac 和 WebApi

c# - 更改禁用 ListView 的背景

asp.net - AntiForgery Token 使用 ASP.NET5 Web API,在 NET46 上没有 System.Web.Helpers

c# - 单元测试调用 session 对象的操作