Minimal ASP.NET Core Web API project

 
 
  • Gérald Barré

ASP.NET Core is created with composition in mind. It means you only use what you need. This is clearly in opposition to the old model where everything was in a single DLL System.Web. The default ASP.NET MVC template allows us to create web pages using razor and also web API. Sometimes, you just need to create an API, so you don't care about Razor, localization, or XML serialization. By removing useless NuGet package and code, you can improve the loading time of your API and reduce the deployment package size.

#Removing useless Nuget packages

First, you have to remove the meta-package Microsoft.AspNetCore.Mvc and add individual packages.

  1. Remove the NuGet package:

    • Microsoft.AspNetCore.Mvc
  2. Add the NuGet packages:

    • Microsoft.AspNetCore
    • Microsoft.AspNetCore.Mvc.Core
    • Microsoft.AspNetCore.Mvc.Formatters.Json
    • Microsoft.AspNetCore.Mvc.ApiExplorer if you want to add web API documentation
    • Microsoft.AspNetCore.Mvc.Cors if you use CORS
    • Microsoft.AspNetCore.Mvc.DataAnnotations if you use validation using Attributes (MaxLengthAttribute, RegularExpressionAttribute, etc.)

#Configuring services

Then, you need to configure the services before you can use them. By default, the AddMvc method is used. This method configures common services. You'll find the code of the method on GitHub.

The idea is to configure every service you need manually. This means, this method depends on the NuGet packages you've added to the project.

C#
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    // Add services in the same order as the AddMvc method
    services.AddMvcCore()
        .AddApiExplorer()     // Optional
        .AddAuthorization()   // Optional if no authentication
        .AddFormatterMappings()
        .AddDataAnnotations() // Optional if no validation using attributes
        .AddJsonFormatters();
        .AddCors()            // Optional
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app)
{
    app.UseMvc();
}

#Testing

You can quickly test the API works great by creating a Controller:

C#
[Route("api/[controller]")]
public class ValuesController
{
    // GET api/values
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
}

Then, start the project and navigate to /api/values. You should see the json response.

#Conclusion

Thanks to the composability of ASP.NET Core, you can use only what you need and so, improve the loading time and reduce the exposition surface of your web application.

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub