.NET core 2.1 web API 是否支持基于约定的路由?

Does .NET core 2.1 web API support convention based routing?

我是 Web API 和 .net core 的新手,我的任务是开发一个 API。

所以我创建了一个默认网站 API(框架:.NET Core 2.1)并尝试添加路由映射,但出现错误。

伙计们谁能帮我做路由。

注意:不能使用基于属性的路由需要像在 MVC 中那样基于约定处理路由

我的启动程序:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        //app.UseHttpsRedirection();
        app.UseMvc(routes =>
        {
        routes.MapRoute(
            name: "default",
            template: "{controller}/{action}/{id?}",
            defaults: new { controller = "Values", action = "dummyaction" });
        });
    }
}

这是我得到的错误:

InvalidOperationException: Action 'myproject.Controllers.ValuesController.dummyaction (myproject)' does not have an attribute route. Action methods on controllers annotated with ApiControllerAttribute must be attribute routed.

您可以使用此示例

namespace TodoApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TodoController : Controller
   {
      [HttpGet("{id}")]
public async Task<ActionResult<TodoItem>> GetTodoItem(long id)
{
//do here
    }
}
}

有关更多信息,请关注此 link

我是如何让它工作的

即使在使用地图路由后,我仍然收到有关基于属性的路由的错误

app.UseMvc(routes =>
    {
    routes.MapRoute(
        name: "default",
        template: "{controller}/{action}/{id?}",
        defaults: new { controller = "Values", action = "dummyaction" });
    });

So in the error can you see this line "Action methods on controllers annotated with ApiControllerAttribute must be attribute routed."

现在在我的控制器中,我正在使用这个特定的 annotation/attribute“[ApiController]”,通过删除它我能够执行基于约定的路由。

另外,我已经将路线更新如下

app.UseMvc(routes =>
{
     routes.MapRoute(
            name: "api",
            template: "api/{controller=Values}/{action=gogogo}/{id?}");
 });

参考文献:

https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-2.2#mixed-routing-attribute-routing-vs-conventional-routing 部分(混合路由:属性路由与常规路由)