Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to inherit from ControllerBase in Web API .NET Core 2.2?

I'm creating a webapi and I wanted to create a controller that inherits from a ControllerBase class.

I'm doing this because I need to do some stuff before calling the action i.e check for the user registration and use the HttpContext.

public class BaseApiZrController : ControllerBase
{
    public BaseApiZrController(ApplicationDbContext db)
    {

        this.HandleAuthentication();

        //??? this.HttpContext is always null, how come?
        ClaimsPrincipal claimsPrincipal = this.HttpContext.User;

    }
    //...some code

 }

Is this a good practice or should I be doing all this in the start class through the middleware?

The other question, when inheriting the ControllerBase class into my custom BaseApiZrController class, I can't accesss the httpContext, it always returns null, how come?

like image 817
Carlo Luther Avatar asked Dec 04 '25 03:12

Carlo Luther


1 Answers

In asp.net core, if we create a web api controller it has ControllerBase by default.

If you want to do something before calling the action, you could use Action Filter or Authorization Filter.Refer to Implementing Action Filters in ASP.NET Core.

HttpContext is not available when the constructor of the Controller is called. See this post.

You could use the IHttpContextAccessor helper service to get the HTTP context in any class that is managed by the ASP.NET Core dependency injection system. This is useful when you have a common service that is used by your controllers.

private readonly IHttpContextAccessor _httpContextAccessor;
    public BaseApiZrController(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
        ClaimsPrincipal claimsPrincipal = _httpContextAccessor.HttpContext.User;
    }

In startup.cs:

public void ConfigureServices(IServiceCollection services)
{
   services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

   // Other code...
}

Refer to Access HttpContext in ASP.NET Core

like image 71
Ryan Avatar answered Dec 06 '25 06:12

Ryan



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!