【问题标题】:Post nested resource and return new location Uri发布嵌套资源并返回新位置 Uri
【发布时间】:2017-07-11 08:51:32
【问题描述】:

我创建了一个 apicontroller,它提供了一个 Post 方法来创建一个新的嵌套资源(在这个例子中:customer > mediaFile):

[Route("api/Customer/{customerId}/MediaFile", Name = "CreateMediaFileForCustomer")]
[HttpPost]
[ResponseType(typeof(MediaFile))]
public IHttpActionResult Post(long customerId, [FromBody]MediaFile mediaFile)
{
    ...

    return CreatedAtRoute("CreateMediaFileForCustomer", new { id = mediaFile.Id }, mediaFile);
}

我希望 CreatedAtRoute 方法返回如下所示的位置标头:

http://localhost:51656/api/Customer/1/MediaFile/37

但是我得到了这个:

http://localhost:51656/api/Customer/1/MediaFile?id=37

经过一番挣扎后,我想出了一个“解决方案”,不知何故感觉像是一种俗气的方法:

[Route("api/Customer/{customerId}/MediaFile/{generatedMediaFileId:long?}", Name = "CreateMediaFileForCustomer")]
[HttpPost]
[ResponseType(typeof(MediaFile))]
public IHttpActionResult Post(long customerId, [FromBody]MediaFile mediaFile)
{
    ...

    return CreatedAtRoute("CreateMediaFileForCustomer", new { generatedMediaFileId = mediaFile.Id }, mediaFile);
}

所以像这样我有一个可选的资源 ID,我只需要正确设置位置标头即可。这是它的工作方式吗?还是有更优雅的解决方案?

谢谢!

【问题讨论】:

    标签: asp.net rest api asp.net-web-api2


    【解决方案1】:

    “CreatedAtRoute”位置标头应返回一个 URL,您可以在其中看到新创建的资源。您使用的路由名称与您的 POST 方法相同。所以我希望看到这样的东西:

    [HttpGet()]
    [Route("api/Customer/{customerId}/MediaFile/{id}", Name="GetMediaFileForCustomer")]
    public IHttpActionResult Get(long customerId, long id)
    {
        ....
    }
    

    您的CreatedAtRoute 将是:

    return CreatedAtRoute("GetMediaFileForCustomer", new { customerId = customerId, id = mediaFile.Id }, mediaFile);
    

    【讨论】:

    • 太好了,非常感谢克雷格!现在我终于明白了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多