如何在asp.net core 3中添加全局路由前缀?

Ale*_*sev 22 routes asp.net-core

UseMvc()用于添加全局路由前缀的旧版 .net 核心框架。如何做到asp.net core 3没有UseMvc()

Rya*_*yan 31

你可以参考下面在asp.net core 3.0中的demo来设置全局路由前缀与api版本。你可以通过改变来设置任何你喜欢的前缀 services.AddControllersWithViews(o => { o.UseGeneralRoutePrefix("api/v{version:apiVersion}"); });

1.创建自定义 MvcOptionsExtensions

public static class MvcOptionsExtensions
{
    public static void UseGeneralRoutePrefix(this MvcOptions opts, IRouteTemplateProvider routeAttribute)
    {
        opts.Conventions.Add(new RoutePrefixConvention(routeAttribute));
    }

    public static void UseGeneralRoutePrefix(this MvcOptions opts, string 
    prefix)
    {
        opts.UseGeneralRoutePrefix(new RouteAttribute(prefix));
    }
}

public class RoutePrefixConvention : IApplicationModelConvention
{
    private readonly AttributeRouteModel _routePrefix;

    public RoutePrefixConvention(IRouteTemplateProvider route)
    {
        _routePrefix = new AttributeRouteModel(route);
    }

    public void Apply(ApplicationModel application)
    {
        foreach (var selector in application.Controllers.SelectMany(c => c.Selectors))
        {
            if (selector.AttributeRouteModel != null)
            {
                selector.AttributeRouteModel = AttributeRouteModel.CombineAttributeRouteModel(_routePrefix, selector.AttributeRouteModel);
            }
            else
            {
                selector.AttributeRouteModel = _routePrefix;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

2.在Startup.cs中注册(需要安装包Microsoft.AspNetCore.Mvc.Versioning,3.0当前版本为4.0.0-preview8.19405.7)

public void ConfigureServices(IServiceCollection services) {
    //MVC service registration
    //https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.0&tabs=visual-studio#mvc-service-registration
    services.AddControllersWithViews(o = >{
        o.UseGeneralRoutePrefix("api/v{version:apiVersion}");
    });

    services.AddApiVersioning(o = >o.ReportApiVersions = true);
}

// 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();
    }

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints = >{
        endpoints.MapControllerRoute(
        name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
        endpoints.MapRazorPages();
    });
}
Run Code Online (Sandbox Code Playgroud)

3.控制器:

[ApiVersion("1")]
[ApiVersion("2")]
[Route("test")]
[ApiController]
public class TestController : ControllerBase
{
    [HttpGet("version"), MapToApiVersion("1")]
    public IActionResult GetV1()
    {
        return new OkObjectResult("Version One");
    }
}
Run Code Online (Sandbox Code Playgroud)

4.结果

调用/api/v1/test/version结果为“版本一”。


ala*_*ree 7

我在 3.1 中解决了这个问题,在我的启动中只使用了以下内容Configure()

app.UsePathBase(new PathString("/api"));
Run Code Online (Sandbox Code Playgroud)

  • 因为它是一个中间件,所以添加顺序很重要。如果我将它添加到 `UseRouting()` 中间件之前,它在 core 3.1 中对我有用。如果之后添加则不起作用。 (2认同)

Mar*_*ijk 7

正如@alastairtree 回答的那样,您可以使用app.UsePathBase它来实现这一点。

您需要在注册需要前缀的中间件之前进行此调用。

如果之后需要注册其他中间件,则不应添加前缀,可以将前缀重置为/.

完整示例:

app.UsePathBase(new PathString("/api"));
app.UseRouting();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller}/{action=Index}/{id?}");
});

app.UsePathBase(new PathString("/"));
app.UseSpa(spa =>
{
    spa.Options.SourcePath = "ClientApp";

    if (env.IsDevelopment())
    {
        spa.UseAngularCliServer(npmScript: "start");
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 目前我实际上不确定这是否正确。无论如何,“UsePathBase”的缺点似乎是带前缀和不带前缀的路径都会导致端点。这可能是也可能不是问题,具体取决于您的用例。就我个人而言,我转而向每个控制器添加前缀:`[Route("api/[controller]")]` (6认同)