When comparing .NET to Python or Node, one of the complaints is the amount of ceremony around setting up a new project. Even the simplest web service is expected to have a Program class, a Startup class, and one or more Controller classes. By contrast, here is a complete Python web service demonstrated by Reddit user ammar2:
from fastapi import FastAPI
import python_weather
app = FastAPI()
@app.get("/api/weather/washington")
async def root():
weather = await python_weather.Client().find("Washington DC")
return weather
In order to compete in low code scenarios, Microsoft has dramatically reduced the amount of code necessary. Here is a minimal example:
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;
var app = WebApplication.Create(args);
app.MapGet("/", (Func<string>)(() => "Hello World!"));
app.Run();
As you can see, the developer doesn’t even need to define a class. Instead, developers can combine C# 9’s top-level statements and a simplified ASP.NET Core API.
Further enhancements in C# 10 will remove the need for the (Func<string>)
casting operation. Here is an example of calling a TODO API using the proposed syntax:
app.MapGet("/api/todos", [Authorize](TodoDbContext db) => db.Todos.ToListAsync());
The above line can be interpreted as:
- Register an HttpGet method on the path /api/todos
- Require the user is authorized
- Inject a DB Context of type TodoDbContext
- Asynchronously return a list of Todo objects from the database
The ASP.NET Core 5 equivalent would be
[ApiController]
[Route("/api/todos")]
public class TodoController : ControllerBase
{
readonly TodoDbContext _db;
public TodoController(TodoDbContext db)
{
_db = db;
}
[HttpGet]
[Authorize]
public Task<Todo> GetAll()
{
return _db.Todos.ToListAsync();
}
}
There are some limitations to this model. For example, there is no place to put the Swagger documentation. Normally this would appear as XML docs on the controllers and their methods. And for larger applications you lose the natural organization of having the REST methods separated into controller classes.
There are also some benefits when it comes to performance. According to Daniel Roth of Microsoft,
These new routing APIs have far less overhead than controller-based APIs. Using the new routing APIs, ASP.NET Core is able to achieve ~800k RPS in the TechEmpower JSON benchmark vs ~500k RPS for MVC.