繁体   English   中英

ASP.NET Core - CreatedAtRoute() - 如何返回相对位置标头?

[英]ASP.NET Core - CreatedAtRoute() - how to return relative location header?

在 ASP.NET core 6 ApiController 中,我使用CreatedAtRoute()作为 POST API 的结果:

[HttpPost]
[ProducesResponseType(typeof(CatalogItem), (int)HttpStatusCode.Created)]
public async Task<ActionResult<CatalogItem>> CreateNewCatalogItemAsync(CatalogItemDto itemDto)
{
  // ...
  return CreatedAtRoute(nameof(GetCatalogItemByIdAsync), new { itemId = item.Id }, item);
}

这会产生一个带有绝对 URL 的位置标头。

所以我的问题是:如何更改它以在 Location 响应标头中返回相对 URL?

所以不是Location: http://foo.bar/api/item/1我想得到Location: /api/item/1

根据评论,似乎没有任何简单的内置解决方案。 因此,我根据这篇文章构建了以下中间件:

app.Use(async (context, next) =>
{
    context.Response.OnStarting(o =>
    {
        if (o is HttpContext ctx)
        {
            // In order to get relative location headers (without the host part), we modify any location header here
            // This is to simplify the reverse-proxy setup in front of the application
            try
            {
                if (!string.IsNullOrEmpty(context.Response.Headers.Location))
                {
                    var locationUrl = new Uri(context.Response.Headers.Location);
                    context.Response.Headers.Location = locationUrl.PathAndQuery;
                }
            }
            catch (Exception) { }
        }
        return Task.CompletedTask;
    }, context);
    await next();
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM