【问题标题】:How to consume ASP.NET Web API in C# which returns an object如何在 C# 中使用返回对象的 ASP.NET Web API
【发布时间】:2015-03-04 19:43:36
【问题描述】:

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

【问题讨论】:

  • 在C#中使用httpclient
  • 尝试使用 response.Content.ReadAsAsync().Result,其中 TResult 是您的预期返回类型。
  • 试着做:Request.CreateResponse(HttpStatusCode.OK, item , new JsonMediaTypeFormatter());
  • @FrebinFrancis - 这些方法是异步工作的,有没有办法以同步方式做同样的事情?我只是想确定是否处理了请求,并在收到响应或超时后做一些事情。等待响应一段时间,然后在收到响应或超时时继续操作,这不是一个好主意吗?

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


【解决方案1】:

试试:

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

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

【讨论】:

  • 这些方法是异步工作的,有没有办法与同步方式一样?
  • 据我所知,在使用 HttpClient 时不会。我完全不确定在这里使用同步方法是否是个好主意。绝对无法知道呼叫需要多长时间才能返回,或者即使它会完全返回。如果你使用同步方法,你会同时阻塞你的线程。
  • 但我的意思是,我只是想确定请求是否得到处理,并在收到响应或超时后做一些事情。等待响应一段时间,然后在收到响应或超时时继续操作,这不是一个好主意吗?
  • 这就是异步/等待模式的工作原理。您的代码会同步运行,直到您使用“等待”标记调用异步方法。它在后台运行您的异步方法并将控制权返回给主线程,以便您的 UI 保持响应。每当您的异步调用完成时,您的代码的其余部分就会运行。如果您对如何使用 async/await 来充分利用答案中的代码有疑问,我建议您开始一个新问题,或者查看一些已经发布的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多