Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between UseRouter and UseEndpoints

Tags:

asp.net-core

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?

like image 340
Sergey Kostrukov Avatar asked Nov 20 '25 06:11

Sergey Kostrukov


1 Answers

As far as I understand:

  • UseRouter is the old way of routing (defined in .net core 2.1)
  • UseEndpoints is the new way of routing (defined in .net core 3.0)

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.

like image 116
SergeyT Avatar answered Nov 22 '25 19:11

SergeyT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!