Skip to content

Commit 760c57d

Browse files
author
DwGoing
committed
✨ feat: 增加全局路由前缀扩展方法
1 parent 138d82f commit 760c57d

File tree

3 files changed

+46
-1
lines changed

3 files changed

+46
-1
lines changed

example/WebExample/Program.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,8 +126,8 @@ public void ConfigureServices(IServiceCollection services)
126126
//不使用驼峰样式的key
127127
options.JsonSerializerOptions.DictionaryKeyPolicy = null;
128128
});
129+
services.AddMvc(options => options.UseRoutePrefix("api"));
129130
services.AddRpcImplements();
130-
131131
services.AddRazorPages();
132132
services.AddServerSideBlazor();
133133
services.AddAntDesign();

src/DwFramework.Web/Extensions/WebExtension.cs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
using Microsoft.AspNetCore.Builder;
44
using Microsoft.AspNetCore.Routing;
55
using Microsoft.AspNetCore.Hosting;
6+
using Microsoft.AspNetCore.Mvc;
7+
using Microsoft.AspNetCore.Mvc.Routing;
68
using Microsoft.Extensions.Configuration;
79
using Microsoft.Extensions.DependencyInjection;
810
using Autofac;
@@ -111,5 +113,15 @@ public static IApplicationBuilder UseWebSocket(this IApplicationBuilder app)
111113
WebService.Instance.UseWebSocket(app);
112114
return app;
113115
}
116+
117+
/// <summary>
118+
/// 使用全局路由前缀
119+
/// </summary>
120+
/// <param name="options"></param>
121+
/// <param name="prefix"></param>
122+
public static void UseRoutePrefix(this MvcOptions options, string prefix)
123+
{
124+
options.Conventions.Insert(0, new RoutePrefix(new RouteAttribute(prefix)));
125+
}
114126
}
115127
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
using System;
2+
using System.Linq;
3+
using Microsoft.AspNetCore.Mvc.Routing;
4+
using Microsoft.AspNetCore.Mvc.ApplicationModels;
5+
6+
namespace DwFramework.Web
7+
{
8+
public sealed class RoutePrefix : IApplicationModelConvention
9+
{
10+
private readonly AttributeRouteModel _centralPrefix;
11+
12+
public RoutePrefix(IRouteTemplateProvider routeTemplateProvider)
13+
{
14+
_centralPrefix = new AttributeRouteModel(routeTemplateProvider);
15+
}
16+
17+
public void Apply(ApplicationModel application)
18+
{
19+
foreach (var controller in application.Controllers)
20+
{
21+
var matchedSelectors = controller.Selectors.Where(x => x.AttributeRouteModel != null).ToList();
22+
if (matchedSelectors.Any())
23+
{
24+
foreach (var selectorModel in matchedSelectors)
25+
{
26+
selectorModel.AttributeRouteModel = AttributeRouteModel.CombineAttributeRouteModel(_centralPrefix,
27+
selectorModel.AttributeRouteModel);
28+
}
29+
}
30+
}
31+
}
32+
}
33+
}

0 commit comments

Comments
 (0)