Get Host Address in ASP.NET Core MVC
You can get by accessing Request
string myurl = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}";
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();
}