如何使用 jquery 从 ASP.Net web api CreatedAtRoute 获取 Id

How to get Id from ASP.Net web api CreatedAtRoute with jquery

我正在尝试学习如何从在 asp.net web api

中创建 post 时创建的路由获取 ID
[ResponseType(typeof(MyDTO))]
public IHttpActionResult PostmyObject(MyDTO myObject)
{
...
return CreatedAtRoute("DefaultApi", new { id = myObject.Id }, myObject);
}

returns 带有位置的 201,但我现在希望能够获取该位置的 ID,而我不知道如何做到这一点

$.ajax({
statusCode: {
201: function() {
  //what to do here?
 }
}
});

您应该使用以下方法检索 location header 的值:

$.ajax({
  statusCode: {
    201: function(data, textStatus, xhr) {
      //what to do here?
      console.log(xhr.getResponseHeader('Location')); 
    }
  }
});