Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to require a header in an ASP.NET API controller

public class GroupsController : ControllerBase
{
    private readonly ILogger<GroupsController> _logger;

    public GroupsController(ILogger<GroupsController> logger)
    {
        _logger = logger;

        string auth = Request.Headers["authorization"];

        if (auth is null) 
             throw new Exception("Missing auth token");
    }

    [HttpGet("/[controller]/allGroups")]
    public List<Group> GetGroups()
    {
        DbContext dbContext = new DbContext();

        List<Group> groups = dbContext.Groups.ToList();

        return groups;
    }
}

I’m looking to require a authorization header only for this controller, but Request is not possible on the constructor and I don’t want to add a auth check on every method on the controller.

Is there a way to check this header on all routes on this controller?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can carate a custom attribute that validates headers and put it on your action or controller that you want to validate headers. like this:

public class RequiredHeaderAttribute : Attribute, IActionFilter
{
    private readonly string _requiredHeader;

    public RequiredHeaderAttribute(string requiredHeader)
    {
        _requiredHeader = requiredHeader;
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        //
    }

    public void OnActionExecuting(ActionExecutingContext context)
    {
        if (!context.HttpContext.Request.Headers.
            TryGetValue(_requiredHeader, out _))
        {
            throw new Exception($"Missing Header Exception: {_requiredHeader}");
        }
    }
}

Usage:

[RequiredHeader("HeaderName")] //<==NOTE THIS
[HttpGet("/[controller]/allGroups")]
public List<Group> GetGroups()
{
    DbContext dbContext = new DbContext();

    List<Group> groups = dbContext.Groups.ToList();

    return groups;
}

Or

[RequiredHeader("HeaderName")]
public class GroupsController : ControllerBase
{
}

Another way is register RequiredHeader as global filters.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading