我正在使用NET Core 3.1创建API应用程序。我想避免在每个ApiControllers和Actions上设置route属性。我在UseEndpoints上尝试了很多组合以设置常规路线,但是我失败了。
如何设置startup.cs以使用其类名自动映射控制器,并使用其方法名来设置Action?
谢谢!
startup.cs
...
services.AddControllers()
...
app.UseHttpsRedirection()
.UseRouting()
.UseAuthentication()
.UseEndpoints(endpoints => ?? )
.UseCoreHttpContext()
.UseServerConfiguration();
controller.cs
[ApiController]
public class BaseAPI : ControllerBase
{
[HttpGet]
public string ApiIsWorking()
{
return "API is working!";
}
}
您在ConfigureServices
方法中应在下面一行:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
您可以在启动时通过configure
方法使用以下配置
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
路由模板{controller=Home}/{action=Index}/{id?}
可以与/Products/Details/5
之类的URL路径匹配,并将通过标记路径来提取路由值{ controller = Products, action = Details, id = 5 }
。
这应该工作。
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" });