ASP.NET Core API 中的常规路由

Pao*_*ati 9 c# asp.net-apicontroller asp.net-core asp.net-core-webapi asp.net-core-3.1

问题:

我正在使用 NET Core 3.1 创建 API 应用程序。我想避免在每个ApiControllers和操作上设置路由属性。我尝试了很多组合UseEndpoints来设置常规路线,但我失败了。

对于某些配置,我无法使 Api 正常工作,而在其他一些配置中,我在启动过程中遇到此异常:

InvalidOperationException:操作“ApiIsWorking”没有属性路由。使用 ApiControllerAttribute 注释的控制器上的操作方法必须进行属性路由。

如何startup.cs使用类名和方法名设置自动映射控制器?

谢谢!

一些代码:

启动文件

...
services.AddControllers()
...

app.UseHttpsRedirection()
   .UseRouting()
   .UseAuthentication()
   .UseEndpoints(endpoints => ?? )
   .UseCoreHttpContext()
   .UseServerConfiguration();
Run Code Online (Sandbox Code Playgroud)

控制器.cs

[ApiController]
public class BaseAPI : ControllerBase 
{
        [HttpGet]
        public string ApiIsWorking()
        {
            return "API is working!";
        }
}
Run Code Online (Sandbox Code Playgroud)

解决方案:

正如 Reza Aghaei 在解决方案中所说,错误是添加了 ApiController 属性。删除它后,命令 UseEndpoints 开始工作。

我的错误是添加属性以便能够识别应通过 API 公开哪些类。这是没有必要的,因为 UseEndpoints 只映射从 ControllerBase 继承的类。

警告:

1)常规路由需要[FromBody]动作参数中的属性。

2) 我强调了 Zinov 对 .NET Core 中 Swashbuckle 的常规路由问题的回应

Rez*_*aei 11

要为您的控制器和动作进行常规路由,您需要从控制器和动作中删除[ApiController]属性和[Route]属性,并在UseEndpoints.

它已经在文档中提到:

[ApiController]属性使属性路由成为一项要求。

行动是经由不可访问常规途径由下式定义UseEndpointsUseMvcUseMvcWithDefaultRouteStartup.Configure

例子

这是我用于启动的工作设置:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }
    public IConfiguration Configuration { get; }
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }
        app.UseStaticFiles();
        app.UseRouting();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

和一个示例 API 控制器:

public class ValuesController : ControllerBase
{
    // values/getall
    [HttpGet]
    public IEnumerable<string> GetAll()
    {
        return new string[] { "value1", "value2" };
    }

    // values/getitem/1
    [HttpGet]
    public string GetItem(int id)
    {
        return "value";
    }
}
Run Code Online (Sandbox Code Playgroud)


Zin*_*nov 5

如果您打算在 .net core 中使用传统路由,这里是我的建议。完成 API 实现后,您将向其中添加一些文档。人们通常使用这个nuget包Swashbuckle.AspNetCore,它实现了OpenAPI(Swagger)的后期标准。但是,当您使用传统路由并且想要使用此工具生成文档时,就会出现问题。

如果您使用传统路由(而不是属性路由),则使用传统路由的任何控制器和这些控制器上的操作都不会在 ApiExplorer 中表示,这意味着 Swashbuckle 将无法找到这些控制器并从中生成 Swagger 操作他们

有关更多信息,请参阅此链接:Swashbuckle 希望这可以为您的 api 文档在将来避免很多麻烦