C# – How to get the status code when using HttpClient

When you use HttpClient to make requests, you can directly get the status code from the HttpResponseMessage object, like this: The main reason for checking the status code is to determine if the request was successful and then reacting to error status codes (usually by throwing an exception). The HttpResponseMessage class has two helpers that … Read more

C# – Handling redirects with HttpClient

HttpClient handles redirects automatically. When you send a request, if the response contains a redirect status code (3xx) and redirect location, then it’ll send a new request to the redirect location. You can turn off this auto-redirect behavior by passing in an HttpClientHandler with AllowAutoRedirect=false. This prevents it from following redirects automatically, and allows you … Read more

ASP.NET Core – How to unit test an action filter

To unit test an action filter, you have to pass in an action filter context object (which requires a lot of setup). Action filter methods are void, so you have to verify the behavior by inspecting the context object (or dependencies, like a logger, if you are injecting those). Here’s an example of doing the … Read more

ASP.NET Core – How to add your own action filter

Action filters allow you to look at requests right before they are routed to an action method (and responses right after they are returned from the action method). The simplest way to add your own action filter in ASP.NET Core is to subclass ActionFilterAttribute and then override the appropriate methods depending on if you want … Read more

C# – How to use Polly to do retries

Whenever you’re dealing with code that can run into transient errors, it’s a good idea to implement retries. Transient errors, by definition, are temporary and subsequent attempts should succeed. When you retry with a delay, it means you think the the transient error will go away by itself after a short period of time. When … Read more

ASP.NET Core – How to unit test your middleware class

There are three requirements for unit testing a middleware class: Mock out RequestDelegate by defining a lambda that returns a Task (Task.FromException, Task.FromResult, or Task.FromCanceled). Mock out HttpContext by using DefaultHttpContext. The middleware function needs to be awaited, so your unit test needs to be defined with async Task. Here’s an example: This is a … Read more

ASP.NET Core – How to unit test an ApiController

The key to unit testing an ApiController class is to mock out all of its dependencies, including the controller’s HttpContext property, like this: If the controller method you’re testing uses anything from the HttpContext, then you’ll want to swap in your own value. Otherwise HttpContext will be null and you’ll get a NullReferenceException. Fortunately Microsoft … Read more