Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the ASP.NET Core 3.1 equivalent to HttpControllerContext and HttpActionContext?

I have migrated the project from Dot.Net-Framework 4.7.2 to Asp.Net-Core 3.1. I want to change all property of ApiController Class in the WebApi.

public static HttpActionContext CreateActionContext(HttpControllerContext controllerContext = null, 
                                                    HttpActionDescriptor actionDescriptor = null)
{
    HttpControllerContext context = controllerContext ?? CreateControllerContext();
    HttpActionDescriptor descriptor = actionDescriptor ?? CreateActionDescriptor();
    descriptor.ControllerDescriptor = context.ControllerDescriptor;
    return new HttpActionContext(context, descriptor);
}

For System.Web.Http, I followed the below link. When I used, it's working, but don't know whether is this right method and below one is not supported in MAC

System.Web.Http missing in .net Core 2.1

Kindly provide any alternative or better solution

like image 865
Karthic G Avatar asked Oct 20 '25 08:10

Karthic G


1 Answers

In controllers and actions you can access the HttpContext using the property HttpContext by inheriting from the base class ControllerBase

While if you needed the HttpContext in other components you have to use dependency injection like this:

public void ConfigureServices(IServiceCollection services)
{
     services.AddHttpContextAccessor();
}

Then by injecting it in the constructor:

public class SomeClass
{
    private readonly IHttpContextAccessor _httpContextAccessor;

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

MsDocs

like image 59
HMZ Avatar answered Oct 21 '25 23:10

HMZ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!