Search code examples
c#asp.net-core-mvc.net-6.0asp.net-core-6.0

Run ASP.NET Core 6 MVC app with attribute route


I have an ASP.NET Core 6 MVC application and when I run my app, I get a http 404 error:

enter image description here

Index action method:

public class HomeController : Controller
{
    [HttpGet]
    [Route("/User/Dashboard")]
    public async Task<IActionResult> IndexAsync()
    {//mycodeishere}
}

The code in the startup.cs:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else 
    {
        app.UseExceptionHandler("/Error");
        app.UseStatusCodePagesWithReExecute("/Error/{0}");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers(); // This maps all controller actions with attribute routing
        });

    app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
}

I keep the attribute route and redirect direct to /client/dashboard when I run the app


Solution

  • When you are applying the [Route("/User/Dashboard")] attribute-route to the Index action method you actually avoid the "default" conventional route for the Index:

    endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    

    It's because the routes defined by the Route attributes have more privilege. Therefore, if want to hit the \Home\Index when entering the localhost:44351 your should declare the default route like below:

    public class HomeController : Controller
    {
        [HttpGet] // might be commented: it's default option
        [Route("")]
        [Route("/User/Dashboard")]
        public async Task<IActionResult> IndexAsync()
        {
        ....
        }
    

    For an additional information see: Routing to controller actions in ASP.NET Core

    Pay attentions on the following sentences in the documentation:

    Actions are either conventionally-routed or attribute-routed. Placing a route on the controller or action makes it attribute-routed. See Mixed routing for more information.