gpt4 book ai didi

c# - 在 ASP.NET Core MVC 中获取主机地址

转载 作者:行者123 更新时间:2023-12-04 17:30:02 25 4
gpt4 key购买 nike

我想在我的 Controller 上获取我的主机地址,类型为 POST。请检查下面的 Controller 示例。请注意我使用的是asp.net core 2.1

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult PasswordReset(ResetPassword data)
{
string myurl = //how can i store http host address on this variable?
return View()
}

最佳答案

尝试这个:

在 Controller 中:

string myHostUrl = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}";

Controller 外:
public class YourClass 
{
private readonly IHttpContextAccessor _httpContextAccessor;
public YourClass(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}

public void YourMethod()
{
string myHostUrl = $"{_httpContextAccessor.HttpContext.Request.Scheme}://{_httpContextAccessor.HttpContext.Request.Host}";
}
}

然后注册 IHttpContextAccessor在 Startup 类中,如下所示:
public void ConfigureServices(IServiceCollection services)
{
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

// Or you can also register as follows

services.AddHttpContextAccessor();
}

关于c# - 在 ASP.NET Core MVC 中获取主机地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53577352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com