使用HttpClient从AspNet WebApi获取创建对象的位置

时间:2017-06-06 08:40:39

标签: c# asp.net-web-api dotnet-httpclient

我获得了发布数据和返回创建对象位置的服务

 public IHttpActionResult Post([FromBody]ErbrachteLeistung value)
{
  int newLeistungId = service.AddErbrachteLeistung(value);
  return Created($"api/ErbrachteLeistung/{newLeistungId}", value);
}

我的客户端看起来像这样

HttpClientHandler handler = new HttpClientHandler
  {
    UseDefaultCredentials = true,
    AllowAutoRedirect = true
  };

  using (HttpClient client = new HttpClient(handler))
  {
    client.BaseAddress = new Uri(WebApiUri);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    HttpResponseMessage response = client.PostAsJsonAsync<ErbrachteLeistung>("api/ErbrachteLeistung", erbrachteLeistung).Result;
    response.EnsureSuccessStatusCode();
  }

如何从响应中读取WebService中给出的创建位置?

1 个答案:

答案 0 :(得分:0)

201 Created响应将该值存储在Location Header

//...
response.EnsureSuccessStatusCode();
Uri location = response.Headers.Location;

//...