Hoping to build a robust, secure, and scalable REST API for your next project? Look no further than ASP.NET Core, Microsoft's modern, cross-platform framework for building web applications and APIs. With its exception handling, model validation, and built-in support for OWIN and Katana middleware, ASP.NET Core is the perfect choice for your REST API development. Let's dive into a comprehensive tutorial that will have you creating and consuming RESTful services on ASP.NET Core in no time.

Before we get started, ensure you have .NET Core SDK 3.1 or later installed on your machine. You can download and install it from the official Microsoft website. With that done, let's create our first ASP.NET Core REST API project.

Setting Up Your First ASP.NET Core REST API Project
Open your terminal or command prompt and run the following command to create a new ASP.NET Core Web API project:

dotnet new webapi -n MyRestApi
Once the project is created, navigate to the project directory using cd MyRest Api and run the application with dotnet run.

Understanding ASP.NET Core's Project Structure
After running the application, you'll notice that a default REST API with a single controller (ValuesController.cs) has been created. This controller contains two actions (Get and GetWithId), each representing a different HTTP endpoint for your API.
ASP.NET Core's project structure follows the{MVC (Model, View, Controller) architectural pattern} by default. However, as we're building an API, we'll primarily be working with the Controllers and Models. The Views component is mostly ignored in API development.

Creating Your First API Controller
To create your first API controller, right-click on the Controllers folder in Solution Explorer, and select Add > Controller. Name it UsersController.cs. Your new controller will have a single action (Get) to start with. Let's modify it to accept both GET and POST requests:
public class UsersController : ControllerBase
{
[HttpGet]
public ActionResult<IEnumerable<User>> Get()
{
// Your GET logic here
}
[HttpPost]
public ActionResult<User> Post(User user)
{
// Your POST logic here
}
}

The [HttpGet] and [HttpPost] attributes correspond to the HTTP methods our endpoints will respond to. The Get and Post methods' parameters are annotated with an action result that returns a list of users or a single user, respectively.
Enhancing Your API with Model Validation









ASP.NET Core provides strong support for model validation. To enable this, you'll first need to create a model class for your users. Add a new class named User.cs to your project with the following code:
public class User
{
public string Name { get; set; }
public string Email { get; set; }
[Required]
[EmailAddress]
public string EmailAddress { get; set; }
}
The [Required] and [EmailAddress] attributes are data annotations that validate the EmailAddress property. If a POST request to your Users controller is made with an invalid email address, ASP.NET Core will automatically return a 400 Bad Request response with error details.
Testing Your API Locally
Now that we've set up our basic API and added model validation, it's time to test our application. Open a new terminal window, navigate to your project directory, and run the following command to start your API:
dotnet run
Once your API is up and running, you can send HTTP requests to https://localhost:5001/users using tools like Postman or curl to test your endpoints.
Securing Your API with Authentication and Authorization
ASP.NET Core provides multiple authentication schemes out of the box, such as cookie, JWT, and OAuth. For this tutorial, we'll use JWT (JSON Web Tokens) and add it to our users controller. First, install the Microsoft.AspNetCore.Authentication.JwtBearer NuGet package. Then, configure your authentication in the Startup.cs file:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = configuration ["Jwt:Issuer"],
ValidAudience = configuration ["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration ["Jwt:Key"]))
};
});
Now, add the [Authorize] attribute to your controller to require JWT authentication for all API calls:
[Route("api/[controller]")]
[ApiController]
[Authorize]
With these changes, your API will now require authenticating clients to access your users controller.
Consuming Your REST API with Swagger
Swagger is a popular open-source tool for describing, testing, and documenting REST APIs. ASP.NET Core provides seamless integration with Swagger through the Swashbuckle.AspNetCore package. Install this package, and add the AddSwaggerDocument and UseSwaggerUI methods to your Startup.cs file:
services.AddSwaggerDocument();
// ... other configurations
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My REST API V1");
});
With these changes, you can access your API documentation at https://localhost:5001/swagger once your API is running.
Testing Your API with Swagger
Swagger provides an intuitive interface for testing your API endpoints. You can send various HTTP requests (GET, POST, PUT, DELETE, etc.) to your API using the Try it out! feature. Swagger will automatically format the request body according to your API's model class, making it easy to test different scenarios.
And there you have it! You've created a RESTful API on ASP.NET Core with model validation, JWT authentication, and Swagger for testing and documentation. The possibilities with ASP.NET Core are endless, so grab your favorite IDE, and happy coding!
Remember to keep your API keys and sensitive data securely stored and managed. Consider using environment variables or secure vault services for better security. Now go forth and build secure, scalable, and maintainable REST APIs with ASP.NET Core!