简体   繁体   中英

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

In an ASP.NET core 6 ApiController I'm using CreatedAtRoute() as a result of a 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);
}

This results in a location header with the absolute URL.

So my question is: How can I change this to return a relative URL instead in the Location response header?

So instead of Location: http://foo.bar/api/item/1 I'd like to get Location: /api/item/1

Based on the comments there does not seem to be any easy, built-in solution. Hence I build the following middleware, based on this post :

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();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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