简体   繁体   中英

Action routing in .Net Core 3 Web API

I am busy migrating an existing-working WebApi from .Net Core 2.2 to 3, however, the routing stopped working. I keep getting a 404 Not Found message.

Would like to use the action names as part of the route template in my controller, for example:

[Route("/api/[controller]/[action]")]

Call example: /api/Lookup/GetBranchesAsync

I'm just really confused about why it stopped working.

Please see the code below.

Startup:

public class Startup
{
  public Startup(IConfiguration configuration)
  {
    Configuration = configuration;
  }

  public IConfiguration Configuration { get; }

  public void ConfigureServices(IServiceCollection services)
  {
    services.AddControllers();

    services.AddScoped<IAuthService, AuthService>();
    services.AddScoped<ILookupService, LookupService>();
    services.AddScoped<IFranchiseRepo, FranchiseRepo>();            
    services.AddScoped<ILogRepo, LogRepo>();

    services.AddSingleton<IConfiguration>(Configuration);           
  }

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

    app.UseHttpsRedirection();
    app.UseRouting();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
  }
}

Controller:

[ApiController]
[Route("/api/[controller]/[action]")]    
[Produces("application/json")]    
public class LookupController : Controller
{
   private readonly ILookupService lookupService;

   public LookupController(ILookupService lookupService)
   {
       this.lookupService = lookupService;
   }

   [HttpGet]
   public async Task<IActionResult> GetBranchesAsync()
   {

   }

   [HttpGet("{branchID}")]
   public async Task<IActionResult> GetBranchSEAsync(int? branchID)
   {

   }
}

Any advice on what the issue could be?

According to https://github.com/aspnet/AspNetCore/issues/8998 , in .NET Core 3.0 Async is skipped by default in Action name. Your endpoint is available at /api/Lookup/GetBranches . You can change this behaviour by replacing

services.AddControllers();

with

services.AddControllers(options => options.SuppressAsyncSuffixInActionNames = false);

in ConfigureServices method, or just use the new routes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM