ASP.NET Core was designed with composition in mind, meaning you only use what you need. This contrasts with the old model where everything was bundled in a single DLL, System.Web. The default ASP.NET MVC template supports both web pages via Razor and Web API endpoints. When you only need to build an API, features like Razor, localization, and XML serialization add unnecessary overhead. By removing unneeded NuGet packages and code, you can improve startup time and reduce the deployment package size.
#Removing unnecessary NuGet packages
Start by removing the Microsoft.AspNetCore.Mvc meta-package and replacing it with individual packages.
Remove the NuGet package:
Add the NuGet packages:
Microsoft.AspNetCoreMicrosoft.AspNetCore.Mvc.CoreMicrosoft.AspNetCore.Mvc.Formatters.JsonMicrosoft.AspNetCore.Mvc.ApiExplorer if you want to add web API documentationMicrosoft.AspNetCore.Mvc.Cors if you use CORSMicrosoft.AspNetCore.Mvc.DataAnnotations if you use validation using Attributes (MaxLengthAttribute, RegularExpressionAttribute, etc.)
#Configuring services
Next, configure each service individually. By default, the AddMvc method sets up all common services. You can find the source on GitHub.
The goal is to register only the services you need. Each method call corresponds to a NuGet package you have 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
To verify the setup, create a simple controller:
C#
[Route("api/[controller]")]
public class ValuesController
{
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
Start the project and navigate to /api/values. You should see a JSON response.
#Conclusion
Thanks to the composability of ASP.NET Core, you can include only what you need, improving startup time and reducing the attack surface of your web application.
Do you have a question or a suggestion about this post? Contact me!