[英]Get absolute URL inside Web API Controller?
在我的 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?
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);
}
我在 .NET 5.0 上,以防萬一。
string baseUrl = $"{Request.Scheme}://{Request.Host.Value}/{Request.Path}";
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.