【发布时间】:2020-05-29 00:38:43
【问题描述】:
问题:
我正在使用 NET Core 3.1 创建一个 API 应用程序。
我想避免在每个 ApiControllers 和 Actions 上设置路由属性。我在UseEndpoints 上尝试了很多组合来设置常规路线,但我失败了。
在某些配置下,我无法让 Api 正常工作,而在其他一些配置下,我在启动时遇到此异常:
InvalidOperationException:操作“ApiIsWorking”没有 属性路线。带有注释的控制器上的操作方法 ApiControllerAttribute 必须是属性路由。
如何设置startup.cs 以自动映射控制器及其类名和操作及其方法名?
谢谢!
一些代码:
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!";
}
}
解决方案:
As Reza Aghaei says in the solution,错误是添加了 ApiController 属性。删除后,命令 UseEndpoints 开始工作。
我的错误是添加了能够识别哪些类应该通过 API 公开的属性。没有必要,因为 UseEndpoints 只映射从 ControllerBase 继承的类。
警告:
1)Conventional Routing require [FromBody] attribute in actions params.
2) 我强调 Zinov's response 关于 .NET Core 中 Swashbuckle 的常规路由问题
【问题讨论】:
-
要为您的控制器和操作设置常规路由,您需要从控制器中删除
[ApiController]属性并在UseEndpoints中设置路由。 -
长话短说,远在千里之外的平台架构师已经为您做出了使用属性路由的设计决策,这是通过使使用传统路由变得令人难以置信的痛苦来强制执行的路由。
标签: c# asp.net-core asp.net-core-webapi asp.net-apicontroller asp.net-core-3.1