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 respond with bad request during controller initialization or smth similar

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.

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 :

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

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