[英]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.