Asp.NET Web API, a framework for building HTTP services, often requires secure access to data. Basic authentication, the simplest form of access control, comes in handy for such needs. Let's dive into a hands-on example of implementing basic authentication in an Asp.NET Web API application.

Before we start, ensure you have the latest version of .NET and Visual Studio installed. We'll be creating a new Web API project and adding basic authentication using the Microsoft.AspNetCore.Authentication.Core package.

Setting Up the Project and Authentication
Start by creating a new Web API project in Visual Studio. Once done, install the Microsoft.AspNetCore.Authentication.Core package via NuGet package manager.

Next, configure the authentication settings in the Startup.cs file under the ConfigureServices(IServiceCollection services) method. Here's how:
Configuring Basic Authentication

Add the following lines within the method to enable authentication and set up the authentication scheme:
services.AddAuthentication("BasicAuthentication").AddScheme("BasicAuthentication", options =>
{
// Configure your options here.
});
Now, your services have been configured to use basic authentication. Next, you need to add it as a middleware in the Configure(IApplicationBuilder app, IWebHostEnvironment env) method.
Adding the Authentication Middleware

Add the following line within the method to add the authentication middleware:
app.UseAuthentication();
Now, your authentication middleware is set up and ready to use. Let's test the authentication in our Web API.
Protecting Web API Controllers

Now that we've set up the authentication let's protect our Web API controllers. To do this, we'll add a simple action filter and decorate our controllers with the [Authorize] attribute.
Creating the Action Filter









Create a new class named BasicAuthenticationAttribute. This class should inherit from AuthorizationFilterAttribute and override the OnAuthorization method. Here's how:
Decorating Controllers with [Authorize]
Now, decorate your controllers with the [Authorize] attribute to protect them. For example:
The final step is to run your application and attempt to access your Web API. You should now be prompted with a basic authentication dialog, asking for your username and password.
With that, you've successfully implemented basic authentication in an Asp.NET Web API application. This hands-on example demonstrates how to set up and configure authentication, protect controllers, and test basic authentication. Now, dive deeper into other authentication options and securing your APIs.