I want to handle requests for a particular path in ASP.NET Core without using controllers.
It seems that I have two options now:
Using the app.UseRouter(r => r.MapPost(...)):
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouter(r => {
r.MapPost("foo/{fooId:int}/bar", (request, response, routeData) =>
{
// My logic
response.StatusCode = StatusCodes.Status200OK;
return Task.CompletedTask;
});
});
}
Using the app.UseEndpoints(e => e.MapPost(...)):
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapPost("foo/{fooId:int}/bar", context =>
{
// My logic
context.Response.StatusCode = StatusCodes.Status200OK;
return Task.CompletedTask;
});
});
}
Both options seem to behave identically.
What is the principal difference between the two and which one should I use?
As far as I understand:
UseEndpoints supports metadata, context.GetEndpoint() and other powerful features. So it is the preferred option.
UPDATE: Starting from .net 6 both of these approaches are no longer recommended and are replaced with Minimal API.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With