Asp Core 3.0 comes with a lot of interesting things in terms of functionality (gRPC, WorkerServices, Identity, a little Blazor), but also with template changes.
One of these changes is the template for Web API, which suffered a small and good transformation.
As soon as the project was created…I was surprised to see the WeatherForecast.cs file. I though...”Oh…I might have chosen the wrong project type”.
But no, .Net Core team decided that there is time to get rid of that ValuesController that had pretty much no significance. Indeed it had ‘REST-ish” structure and it returned some data but that was it.
The new Web Api project comes with a few changes.
The new controller has only the action that responds to GET requests and returns an IEnumerable
private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" };
In terms of controller actions:
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(\-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
In Startup.cs you will see a lot of new things:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration \= configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints \=>
{
endpoints.MapControllers();
});
}
}
Unlike previous versions, you won't see the UseMvc() extension method in
ConfigureServices in Startup.cs, which added the conventions necessary for routing( as we were used to from MVC).
Now this is replaced by a call to AddControllers(), which as the name implies will add only the controller part needed in a Web Api Project.
There are several options in
MvcServiceCollectionExtensions class: AddMvc(), AddControllersWithViews() or AddRazorPages()
app.UseEndpoints() is a new extension of IApplicationBuilder that dispatches requests. More than that, the configuration part of an endpoint has been moved here from app.UseRouting().
The configuration endpoints.MapControllers(); maps attribute routing controller.
These are not major changes, and I personally enjoy how the .NET team is doing their best to make everything as configurable and performant as they can.
Hi! Welcome to my blog