[英]Get absolute URL inside Web API Controller?
In my Controller I can't use CreatedAtAction
for reasons out of the scope of this question.在我的 Controller 中,出于此问题的 scope 的原因,我无法使用
CreatedAtAction
。 I therefore need to do the following, however I don't know how to get the absolute URL of the Web API to correctly set the Location
header? I therefore need to do the following, however I don't know how to get the absolute URL of the Web API to correctly set the
Location
header?
public async Task<ActionResult<string>> PostItem(ItemPostRequest itemPostRequest)
{
// call repository etc.
string baseUrl= // <------- how to get this?
Response.Headers.Add("Location", baseUrl + insertId);
return Content(savedItem, "application/json", System.Text.Encoding.UTF8);
}
I am on .NET 5.0, in case this matters.我在 .NET 5.0 上,以防万一。
string baseUrl = $"{Request.Scheme}://{Request.Host.Value}/{Request.Path}";
Stefan, I cannot add a comment due to low rep, so to add on to the answer from Prasad in your search of a more comfortable solution regarding the trailing slash - this is what I use: Stefan,由于代表率低,我无法添加评论,因此在您寻找关于尾随斜杠的更舒适解决方案时添加 Prasad 的答案 - 这就是我使用的:
using System;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace GeddesCapital.Blas.Api.Controllers
{
public abstract class BaseControllerInheritedByAllMyControllers : ControllerBase
{
protected string BaseUrl => $"{Request.Scheme}://{Request.Host.Value}";
protected string EndpointUrl => $"{BaseUrl}/{Request.Path.ToString().Trim('/')}";
}
[Route("api/v1/[controller]")]
public class TestController : BaseControllerInheritedByAllMyControllers
{
[HttpPost("named-test-endpoint")]
[AllowAnonymous]
public ActionResult SomeTestEndpoint()
{
const string trailingUrl = "/api/v1/Test/named-test-endpoint";
var absoluteUrl1 = $"{BaseUrl}{trailingUrl}";
var absoluteUrl2 = $"{EndpointUrl}";
Console.WriteLine($"The two paths match each other: {absoluteUrl1 == absoluteUrl2}");
return Ok();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.