c# - .NET Core 2.1 Web API 是否支持基于约定的路由?

标签 c# .net asp.net-core asp.net-web-api asp.net-web-api-routing

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

所以我创建了一个默认的 Web 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.

最佳答案

我是如何让它工作的

即使在使用 map route 之后,我仍然收到关于基于属性的路由的错误

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."

现在在我的 Controller 中,我正在使用这个特定的注释/属性“[ApiController]”,通过删除它我能够执行基于约定的路由。

此外,我已将路线更新如下

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

引用资料:

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

asp.net core web api center routing

关于c# - .NET Core 2.1 Web API 是否支持基于约定的路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57730797/

相关文章:

javascript - 仅针对 1 个事件按钮禁用 onbeforeunload 事件

.net - Entity Framework SELECT 1 AS C1

c# - 使用 Entity Framework : “No database provider has been configured for this DbContext” 配置 ASP.NET Core

.net - Docker 没有在它所说的端口上托管任何东西,这是怎么回事?

C# 索引超出范围 String Array 和 List<string>

c# - 在 Azure 存储客户端 2.0 中将一个 Azure blob 复制到另一个 blob

c# - 如何提高EF中查询的执行速度

c# - 如何将复选框控件添加到数据表?

java - 除了从C#移植到Java之外,还有其他更好的选择吗?

css - 如何在 asp.net core 中使用 .less 文件?