Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Host Address in ASP.NET Core MVC

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()
}
like image 595
John Doe Avatar asked Dec 02 '18 04:12

John Doe


People also ask

What is host in ASP.NET Core?

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.

How can get HttpContext current in ASP.NET Core?

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.


1 Answers

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();
}
like image 102
TanvirArjel Avatar answered Oct 06 '22 01:10

TanvirArjel