I want to get my host address on my controller which type is POST. Please check bellow the controller example. Please note I am using 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()
}
The host is responsible for app startup and lifetime management. At a minimum, the host configures a server and a request processing pipeline. The host can also set up logging, dependency injection, and configuration. This article covers the Web Host, which remains available only for backward compatibility.
In ASP.NET Core, if we need to access the HttpContext in service, we can do so with the help of IHttpContextAccessor interface and its default implementation of HttpContextAccessor. It's only necessary to add this dependency if we want to access HttpContext in service.
Try this:
In the controller:
string myHostUrl = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}";
Outside the 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}";
}
}
And then register IHttpContextAccessor
in the Startup class as follows:
public void ConfigureServices(IServiceCollection services)
{
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// Or you can also register as follows
services.AddHttpContextAccessor();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With