【问题标题】:Configuring Multiple HttpVerbs using EndPoint Routing in ASP.Net Core 3.0在 ASP.Net Core 3.0 中使用端点路由配置多个 HttpVerb
【发布时间】:2020-03-26 13:29:01
【问题描述】:

当我在新设置的 WebApi 项目的帐户控制器中使用 Visual Studio 中的默认模板有多个具有相同动词(即 POST)的操作方法时,我遇到了异常。以下是关于 VS 的信息:

Microsoft Visual Studio Enterprise 2019
Version 16.3.10
VisualStudio.16.Release/16.3.10+29519.87

这是我得到的例外:

InvalidOperationException: The method 'post' on path '/api/Account' is registered multiple times.

这是我在启动文件中的默认路由设置:

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

我也尝试了以下方法,但没有帮助。

  endpoints.MapControllerRoute(
            name: "api",
            pattern: "{controller}/{id?}");

endpoints.MapControllerRoute(
            name: "api",
            pattern: "{controller}/{action}/{id?}");

我也在官方文档中阅读了有关端点路由的信息,但我无法弄清楚我错过了什么。感谢您的帮助。

【问题讨论】:

    标签: .net asp.net-core .net-core asp.net-core-webapi asp.net-core-3.0


    【解决方案1】:

    您需要传递模板名称,即[HttpPost("my-other-route")]

    【讨论】:

    • ASP.Net Core WebAPI 中的所有操作方法都需要使用路由属性吗?
    • @SuperCoder Route 属性意味着所有 HTTP 动词都被接受,并且通常(至少根据我的经验)在控制器上使用。 Http(Verb) 属性用于控制器操作。如果您在同一个控制器上使用相同的 HTTP 动词有多个操作,则它们的路由模板必须是唯一的。
    【解决方案2】:

    尝试将Route 属性更改为Controller,如图所示

    [Route("api/[controller]/[action]")]
    [ApiController]
    public class StudentsController : ControllerBase
    { ... }
    

    您可以使用https://localhost:44346/api/students/postStudent 之类的请求路由调用PostStudent 操作,并使用https://localhost:44346/api/students/postStudentList 之类的请求路由调用PostStudentList 操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-23
      • 2020-05-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-29
      相关资源
      最近更新 更多