LPLN
LPLN

Reputation: 473

How to do custom routing in ASP.NET Core 3.1 MVC

I can't use simple routing like in .NET Core 2.2 in .NET Core 3.1.

What is the routing last change in .NET Core 3.1?

Upvotes: 3

Views: 10325

Answers (2)

Hamed Hajiloo
Hamed Hajiloo

Reputation: 1028

In .NET 3 you should use Endpoint instead of Routing

app.UseStaticFiles();
app.UseRouting();
//other middleware

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
    endpoints.MapRazorPages();
    endpoints.MapHub<MyChatHub>();
    endpoints.MapGrpcService<MyCalculatorService>();
    endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
});

Upvotes: 17

Pieter van Kampen
Pieter van Kampen

Reputation: 2077

Next to Endpoint's you can also use attribute routing, or combine the two.

[Route("my/")]
public class MyController : Controller

[HttpGet]
[AllowAnonymous]
[Route("")] //prefer this if we asked for this action
[Route("index", Order = 1)]
[Route("default.aspx", Order = 100)] // legacy might as well get an order of 100
public async Task<IActionResult> GetIndex()
{
}

With the above attribute for the controller, you do not need to specify MapControllerRoute for this controller. The action has three routes in this example.

Upvotes: 4

Related Questions