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
In ASP.NET, you can add your own feature flags by using the feature management functionality. In this article, I’ll show how to configure and use feature management in ASP.NET and how to use this to feature gate an endpoint using your own feature flag. Configure feature management You need to do a few configuration steps … Read more
To add User Secrets in an ASP.NET project in Visual Studio do the following steps: Right-click the project and click Manage User Secrets. This will create and open a file called secrets.json. Override appsettings.json settings by putting them in secrets.json For example, let’s say your appsettings.json looks like this: You want to override ApiKey. In … Read more
In ASP.NET, when you need a long-running background task, or need to run a task periodically, you can implement IHostedService or BackgroundService and register your class as a hosted service in Startup. As you may have already encountered, if you try to run a long-running background task, the web server will randomly kill your task … Read more
Problem You’re trying to do synchronous IO operations in ASP.NET and you get the following exception: System.InvalidOperationException: ‘Synchronous operations are disallowed. Call WriteAsync or set AllowSynchronousIO to true The reason you’re getting this is because server option AllowSynchronousIO is false. Starting in ASP.NET Core 3.0, this is false by default. Solution Microsoft turned this setting … Read more
The simplest way to enable CORS for all endpoints is by adding a default CORS policy in the Startup class. The following code shows the two lines of code to add: Note: Put whatever CORS policy makes sense for you. In the code above, I am simply allowing everything. Test CORS locally To test this … Read more
The simplest way to add API documentation is to use Swagger. You can configure it to generate an API documentation page and even send requests to your endpoints. Here’s what it looks like: In this article I’ll show how to install and configure Swagger with the following features (shown in the image above): Generates an … Read more
Problem In IIS Manager, Windows Authentication is missing from the list of available authentication methods. Solution 1. Open Turn Windows features on or off. 2. Select the Windows Authentication feature and click OK. 3. Restart your computer. Once it reboots, you’ll see the Windows Authentication option in IIS.