Search code examples
c#asp.net-coreaspnetboilerplatehttpcontextabp-framework

Accessing the HttpContext in Application Service layer


I'm using the ASP.NET Boilerplate (ASP.NET Core) to create a CRM for the leads to go into.

These leads are pushed into the system via the API (Application Service layer, not the dynamic API).

I had planned on running a quick lookup on the lead source using request URL (from HttpContext) as its a required field in my model.

My question is: What's the best way to get the request URL (origin) of the post request in Application Service layer?

An example is as follows:

public class AboutModel : PageModel
{
    public string Message { get; set; }

    public void OnGet()
    {
        Message = HttpContext.Request.PathBase;
    }
}

Solution

  • Inject and use IHttpContextAccessor.

    public class AboutModel : PageModel
    {
        public string Message { get; set; }
    
        protected HttpContext HttpContext => _httpContextAccessor.HttpContext;
        private readonly IHttpContextAccessor _httpContextAccessor;
    
        public AboutModel(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }
    
        public void OnGet()
        {
            Message = HttpContext.Request.PathBase;
        }
    }