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

Asp.net core 如何在asp.net core 3中添加全局路由前缀?,asp.net-core,routes,Asp.net Core,Routes,旧式.net核心框架使用UseMvc()添加全局路由前缀。如何使asp.net core 3不使用UseMvc()?您可以参考asp.net core 3.0中的以下演示,使用api版本设置全局路由前缀。您可以通过更改services.AddControllersWithViews(o=>{o.UseGeneralRoutePrefix(“api/v{version:apiVersion}”);}来设置任意前缀 1.创建自定义的MvcOptionsExtensions public静态类mvco

旧式.net核心框架使用
UseMvc()
添加全局路由前缀。如何使
asp.net core 3
不使用
UseMvc()

您可以参考asp.net core 3.0中的以下演示,使用api版本设置全局路由前缀。您可以通过更改
services.AddControllersWithViews(o=>{o.UseGeneralRoutePrefix(“api/v{version:apiVersion}”);}来设置任意前缀

1.创建自定义的
MvcOptionsExtensions

public静态类mvcoptionsexpressions
{
public static void UseGeneralRoutePrefix(此MvcOptions选项,IRouteTemplateProvider routeAttribute)
{
添加(新的RoutePrefixConvention(routeAttribute));
}
公共静态void UseGeneralRoutePrefix(此MvcOptions选项,字符串
前缀)
{
选择UseGeneralRoutePrefix(新RouteAttribute(前缀));
}
}
公共类RoutePrefixConvention:IApplicationModelConvention
{
私有只读属性Outemodel\u routePrefix;
公共路由PrefixConvention(IRoutTemplateProvider路由)
{
_routePrefix=新属性Outemodel(路由);
}
公共无效应用(应用程序模型应用程序)
{
foreach(application.Controllers.SelectMany中的var选择器(c=>c.Selectors))
{
if(selector.AttributeRouteModel!=null)
{
selector.AttributeRouteModel=AttributeRouteModel.CombineAttributeOuterModel(_routePrefix,selector.AttributeRouteModel);
}
其他的
{
selector.AttributeRouteModel=\u routePrefix;
}
}
}
}
2.在Startup.cs中注册(您需要安装软件包,3.0的当前版本为4.0.0-preview8.19405.7)

public void配置服务(IServiceCollection服务){
//MVC服务注册
//https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.0&tabs=visual studio#mvc服务注册
services.addcontrollerswithview(o=>{
o、 UseGeneralRoutePrefix(“api/v{version:apiVersion}”);
});
services.AddApiVersioning(o=>o.ReportApiVersions=true);
}
//此方法由运行时调用。使用此方法配置HTTP请求管道。
公共无效配置(IApplicationBuilder应用程序,IHostingEnvironment环境){
if(env.IsDevelopment()){
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(端点=>{
endpoints.MapControllerRoute(
名称:“默认”,模式:{controller=Home}/{action=Index}/{id?});
endpoints.MapRazorPages();
});
}
3.控制员:

[ApiVersion(“1”)]
[第二版]
[路线(“测试”)]
[ApiController]
公共类TestController:ControllerBase
{
[HttpGet(“版本”),MapToApiVersion(“1”)]
public IActionResult GetV1()
{
返回新的OkObjectResult(“版本一”);
}
}
4.结果


调用
/api/v1/test/version
会得到“版本一”。

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


Asp.net core 3.0使用了
app.UseEndpoints()
,您想实现什么全局路由前缀?准确地回答了我的问题!这对我不起作用。我在这里发现了一些变化。。。但这些对我也不起作用,因为这是一个中间件,添加顺序很重要。如果我将它添加到
UseRouting()
中间件之前,那么它在core 3.1中对我有效。如果在之后添加,它将不起作用。
app.UsePathBase(new PathString("/api"));