From Attribute routing vs conventional routing:
It's typical to use conventional routes for controllers serving HTML pages for browsers, and attribute routing for controllers serving REST APIs.
From Build web APIs with ASP.NET Core: Attribute routing requirement:
The [ApiController]
attribute makes attribute routing a requirement. For example:
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
Actions are inaccessible via conventional routes defined by UseEndpoints
, UseMvc
, or UseMvcWithDefaultRoute
in Startup.Configure.
If you want to use conventional routes for web api , you need to disable attribute route on web api.
StartUp:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "Default",
pattern: "{controller=default}/{action=Index}/{id?}");
});
}
Web api controller:
//[Route("api/[controller]")]
//[ApiController]
public class DefaultController : ControllerBase
{
public ActionResult<string> Index()
{
return "value";
}
//[HttpGet("{id}")]
public ActionResult<int> GetById(int id)
{
return id;
}
}
This could be requested by http://localhost:44888/default/getbyid/123
options.EnableEndpointRouting = false
? Because that tells the framework to continue using the 'old' routing, instead of endpoint routing. – Iorio