C#NET Core 3 Api中的UseEndpoints

问题描述 投票:0回答:1

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

如何设置startup.cs以使用其类名自动映射控制器,并使用其方法名来设置Action?

谢谢!

startup.cs

...
services.AddControllers()
...

app.UseHttpsRedirection()
   .UseRouting()
   .UseAuthentication()
   .UseEndpoints(endpoints => ?? )
   .UseCoreHttpContext()
   .UseServerConfiguration();

controller.cs

[ApiController]
public class BaseAPI : ControllerBase 
{
        [HttpGet]
        public string ApiIsWorking()
        {
            return "API is working!";
        }
}
c# asp.net-apicontroller asp.net-core-3.1
1个回答
0
投票

您在ConfigureServices方法中应在下面一行:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
}

您可以在启动时通过configure方法使用以下配置

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

路由模板{controller=Home}/{action=Index}/{id?}可以与/Products/Details/5之类的URL路径匹配,并将通过标记路径来提取路由值{ controller = Products, action = Details, id = 5 }


0
投票

这应该工作。

    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller}/{action}/{id?}",
        defaults: new { controller = "Home", action = "Index" });
© www.soinside.com 2019 - 2024. All rights reserved.