'HttpContext.Current.Request.Url.AbsoluteUri Equivalent in ASP.Net Core MVC

I have converted below ASP.Net MVC code to ASP.Net Core MVC, but I'm getting error like

'HttpContext' does not contain a definition for 'Current' and no accessible extension method 'Current' accepting a first argument of type 'HttpContext' could be found (are you missing a using directive or an assembly reference?)

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;

public class MMAPIController : ControllerBase
{
    public IConfiguration _config;
    public MMAPIController(IConfiguration iConfig)
    {            
        _config = iConfig;
    }

    public string AbsolutePath = HttpContext.Current.Request.Url.AbsoluteUri.Replace("%20", "");
    public void SuccessMessage(int personnelSK)
    {
       if (Logging)
       SmartLogger.Info(DateTime.Now.ToString("dd/MM/yy HH:mm:ss") + " Enter API- " + AbsolutePath + "  User Id- " + personnelSK);
    }
}

I have added this namespace using Microsoft.AspNetCore.Http;.

enter image description here



Solution 1:[1]

If your code is in a controller, then it should inherit from ControllerBase so you can access the request directly as a protected property:

string absolutePath = Request....

If you are in another class you can access the HttpContext by injecting the IHttpContextAccessor into your constructor (as long as you are getting your class instance through DI):

public class MyClass
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public MyClass(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    ...
    // your code
    string absolutePath = _httpContextAccessor.HttpContext.Request....
}

But you will need to ensure this is registered at startup using:

services.AddHttpContextAccessor();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Steve Harris