Posts

Showing posts with the label middleware

.NET Global Exception Handling: 3 Techniques Beyond Try/Catch Blocks

Image
  Exceptions are a big part of any software solution. They happen sometimes because something went wrong like out of memory exceptions and sometimes, they happen because of the domain or the business such as validation exceptions. Either way it is something that must be planned ahead in any system design. And by planning I definitely don't mean sprinkling try/catch blocks all over your code. In this post I will explain three different techniques that will help you to globally handle exceptions and turn the messy response that exceptions return by default to a much organized and concise response. However, note that this does not mean that you should not stop using try/catch blocks if you need them for specific exception handling for specific cases. Our main focus is to manage to run some sort of logic that runs each time an exception occurs so that it prevents the default behavior and instead logs the full exception stack trace and only returns concise readable information for t...

Google & Microsoft Token Validation Middleware in ASP.NET Applications

Image
   I have been working on a web app that allows 3rd party login. I had to validate the token that existed in the authorization header of each request hitting my backend services. The frontend team handled the 3rd party login and obtained a token from one of two providers: Google or Microsoft. Middleware The first step I decided to create middleware that intercepts all calls to my applications to validate the token before taking any further steps. And because ASP.NET Core calls middlewares in order just like a pipeline so it's very important to register this middleware before any other middleware you would like to register, so as not to do any unnecessary processing of requests which are yet to be authenticated. So basically, I created a class inside my API project under a folder named  TokenHandling. And right away always remember to register your middleware/services because sometimes you get  caught up in applying your solution that miss the step where you register ...