public abstract class AbstractController: Controller
{
protected AbstractController(IHttpContextAccessor accessor)
{
var someIdClaim = accessor.HttpContext?.User?.Identities.First().Claims
.FirstOrDefault(s => s.Type == "some_id");
if (String.IsNullOrEmpty(someIdClaim))
// respond with bad request and dont attach to corresponding action method
}
}
Using asp net core 7.
There will be several controllers that will be deriving from this controller.
Obviously, this check could be in a middleware or something too. I just need this check to run for controllers that derive from this abstract controller.
>Solution :
We could maybe help you more if you give more details about WHY are you trying to do this.
Best solution (with some assumptions):
Assuming that what you want is to always ensure that your requests contain a specific claim, and return a Bad Request otherwise, I’d say that the best option is to use a Filter or a Middleware
Use a filter if you want to apply this only to specific endpoints or controllers, with an attribute. Use a middleware if ALL your endpoints should behave like this.
Hackish solution:
As said in a comment, you can’t return anything from a constructor. What you can do, though, is to throw an exception. That, by default will result in a 500 response (internal server error), would that meet your requirements?
However I’d say that generally speaking this is a bad approach, since you are telling the client that you made an error (500) while in fact the claim that you are checking makes me think that the request contained an error (and thus the response should be a 40x, as you proposed in your question).