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?
>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.