Ashish Rathi
Ashish Rathi

Reputation: 1528

Attribute routing is not working properly in asp.net core 3.0

I was trying to migrate my application from asp.net core 2.1 to 3.0 which uses attribute routing

My Startup file's ConfigureServices and Configure methods:

public void ConfigureServices(IServiceCollection services)
{
    services.ConfigureOptions(typeof(ABCClass));
    services.AddTransient<ITagHelperComponent, XYZTagHelperComponent>();            
    services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
       app.UseDeveloperExceptionPage();
    }
    app.UseStaticFiles();
    app.UseMvcWithDefaultRoute();
}

I have replaced services.AddMvc(); with services.AddMvc(options => options.EnableEndpointRouting = false); to disable Endpoint routing

My action method:

[Route("")]
[Route("Machines")]
public async Task<ViewResult> GetMachinesAsync()
{
    return View("MachineView");
}

First time my application loads with MachineView, but when I try to call same action method on it gives me 404 error (page can’t be found)

action call from .cshtml file:

<li class="nav-item">
    <a class="nav-link"
       href="@Url.Action("GetMachinesAsync", "Machine")">
       Machines 
    </a>
</li>

Can you please help me out if I am missing something here, or I have done something wrong while configuring middleware for routing.

Thanks in Advance.

Upvotes: 1

Views: 129

Answers (2)

Anuraj
Anuraj

Reputation: 19618

You don't require async suffixes for action methods. So if you want to refer GetMachinesAsync you need to use GetMachines, like this.

<li class="nav-item">
    <a class="nav-link"
       href="@Url.Action("GetMachines", "Machine")">
       Machines 
    </a>
</li>

Upvotes: 1

Ryan
Ryan

Reputation: 20141

Async suffix for controller action names will be trimmed by default in asp.net core 3.0.

Refer to https://stackoverflow.com/a/59024733/10158551

Solution1:

Replace GetMachinesAsync to GetMachines in view.

<li class="nav-item">
 <a class="nav-link"
   href="@Url.Action("GetMachines", "Machine")">
   Machines 
</a>
</li>

Solution2:

Keep using GetMachinesAsync

<li class="nav-item">
<a class="nav-link"
   href="@Url.Action("GetMachinesAsync", "Machine")">
   Machines 
</a>
</li>

then disable that behavior in startup

services.AddMvc(options =>
{
     options.EnableEndpointRouting = false;
     options.SuppressAsyncSuffixInActionNames = false;
});

Upvotes: 1

Related Questions