我想在我的控制器上获取主机地址,其类型为POST。请检查以下控制器示例。请注意,我正在使用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()
}
答案 0 :(得分:3)
尝试一下:
在控制器中:
string myHostUrl = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}";
控制器外部:
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}";
}
}
然后按如下所示在Startup类中注册IHttpContextAccessor
:
public void ConfigureServices(IServiceCollection services)
{
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// Or you can also register as follows
services.AddHttpContextAccessor();
}
答案 1 :(得分:2)
您可以通过访问请求获得
string myurl = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}";
答案 2 :(得分:1)
//获得完整的主机
string host = Request.Scheme + "://" + Request.Host.Value;
答案 3 :(得分:0)
In case, if your application is hosted inside a virtual directory,
public class ABC
{
private readonly IHttpContextAccessor _httpContextAccessor;
public ABC(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public void GetFullAppHostUrl()
{
string fullUrl= $"{_httpContextAccessor.HttpContext.Request.Scheme}://{_httpContextAccessor.HttpContext.Request.Host}{_httpContextAccessor.HttpContext.Request.PathBase}";
}
}