【问题标题】:REST API controller name discarded (ignored)REST API 控制器名称被丢弃(忽略)
【发布时间】:2021-07-23 14:40:24
【问题描述】:

在 REST API 项目 dotnet Core 5.0 中,我有两个控制器:MyAController 和 MyBController 在不同的类中。它们从派生自 ControllerBase 的 MediatorApiController 派生。除了它们管理的实体 (CRUD) 之外,它们基本上是相同的。当我键入 https://localhost:5001/api 时,它会转到 MyAController 中的 [HttpGet("/{lang}")] 对应方法并显示对象 {lang}='api' ??。

如果我输入 https://localhost:5001/api/MyA/1 或 https://localhost:5001/api/MyB/1 我会收到错误 Microsoft.AspNetCore.Routing.Matching.AmbiguousMatchException:请求匹配多个端点 MyAController.Get MyBController.Get ???

谁能帮忙? 我确实使用了 edi.routedebugger,但它没有得到它(错误 500),如果我显示控制器,它们都会正确显示。

 public class AController : MediatorApiController
 public class BController : MediatorApiController
 public class MediatorApiController : ControllerBase

 
 [Route("api/[controller]")]
 [ApiController]
 public class MyAController : MediatorApiController
 {
    [HttpGet("/{lang}")]
    public async Task<ActionResult<List<AlimentDto>>> GetAll(string lang)
    {
        return await Mediator.Send(new GetAllAlimentsQuery(lang));
    }

    [HttpGet("/{id}/{lang}")]
    public async Task<ActionResult<AlimentDto>> Get(int id, string lang)
    {
      return await Mediator.Send(new GetAlimentByIdQuery { Id = id, Lang = lang });
    }

}

startup.cs 文件:

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwaggerUi3();
                app.UseRouteDebugger();
            }
            //app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

            app.UseOpenApi();
            app.UseHttpsRedirection();

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

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

【问题讨论】:

    标签: .net-core controller rest


    【解决方案1】:

    试着去掉“/”,把它改成

     [HttpGet("{lang}")]
    public async Task<ActionResult<List<AlimentDto>>> GetAll(string lang)
    

    对于 lang=en,您的网址应该是

    ../api/MyAControlle/en
    

    但我更喜欢并推荐使用完整的路由属性

     [Route("~/api/MyAControlle/GetAll/{lang}]
    public async Task<ActionResult<List<AlimentDto>>> GetAll(string lang)
    

    【讨论】:

    • 谢谢 Serge,为什么我没有在 httpGet 中看到那个多余的斜线? localhost:5001/api/myA/enlocalhost:5001/api/myA/1/en 在删除斜线后工作正常。现在很明显,斜线从控制器本身开始位于路由之上。
    • @Eugene 欢迎您。如果它对您有用,请不要忘记接受答案(单击我的答案旁边的复选标记)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 2020-11-23
    • 2014-04-24
    • 2018-12-15
    • 2018-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多