简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM