Minimal ASP.NET Core Web API project

ASP.NET Core is created with composition in mind. It's mean you only use what you need. This is cleary in opposition to the old model where everything was in a single dll System.Web. The default ASP.NET MVC template allows 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 metapackage Microsoft.AspNetCore.Mvc and add individual packages.

  1. Remove the NuGet package:
  • Microsoft.AspNetCore.Mvc
  1. 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 every 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.

// 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:

[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 surface of exposition of your web application.

Leave a reply