Lio*_*ion 14 url routing asp.net-core-mvc asp.net-core
ASP.NET Core 默认使用类似http:// localhost:5000/DashboardSettings/Index的CamelCase-Routes .但我想使用小写路由,这些路由由破折号分隔:http:// localhost:5000/dashboard-settings/index它们更常见且一致,因为我的应用程序扩展了一个运行Wordpress的网站,该网站也有小写网址破折号.
我了解到我可以使用路由选项将URL更改为小写:
services.ConfigureRouting(setupAction => {
setupAction.LowercaseUrls = true;
});
Run Code Online (Sandbox Code Playgroud)
这有效,但给了我网址没有任何分隔符,如http:// localhost:5000/dashboardsettings/index,这些分隔符很难读.我可以使用路由属性来定义自定义路由
[Route("dashboard-settings")]
class DashboardSettings:Controller {
public IActionResult Index() {
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
但这会导致额外的工作并且容易出错.我更喜欢一个自动解决方案,它搜索大写字符,在它们之前插入一个破折号并使大写字母小写.对于旧的ASP.NET来说,这不是一个大问题,但在ASP.NET Core上,我看不到如何处理这个问题的方向.
这是怎么做到这里的?我需要一些接口,我可以生成url(比如标记帮助器)并用dash-delimiters替换CamelCase.然后我需要另一种接口用于路由,以便将破折号分隔符URL转换回CamelCase,以便与我的控制器/动作名称正确匹配.
Tan*_*jel 30
为此,首先创建的SlugifyParameterTransformer类应如下所示:
public class SlugifyParameterTransformer : IOutboundParameterTransformer
{
public string TransformOutbound(object value)
{
// Slugify value
return value == null ? null : Regex.Replace(value.ToString(), "([a-z])([A-Z])", "$1-$2").ToLower();
}
}
Run Code Online (Sandbox Code Playgroud)
对于 ASP.NET Core 2.2 MVC:
在类的ConfigureServices方法中Startup:
services.AddRouting(option =>
{
option.ConstraintMap["slugify"] = typeof(SlugifyParameterTransformer);
});
Run Code Online (Sandbox Code Playgroud)
并且路由配置应该如下:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller:slugify}/{action:slugify}/{id?}",
defaults: new { controller = "Home", action = "Index" });
});
Run Code Online (Sandbox Code Playgroud)
对于 ASP.NET Core 2.2 Web API:
在类的ConfigureServices方法中Startup:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.Conventions.Add(new RouteTokenTransformerConvention(new SlugifyParameterTransformer()));
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
Run Code Online (Sandbox Code Playgroud)
对于 ASP.NET Core >=3.0 MVC:
在类的ConfigureServices方法中Startup:
services.AddRouting(option =>
{
option.ConstraintMap["slugify"] = typeof(SlugifyParameterTransformer);
});
Run Code Online (Sandbox Code Playgroud)
和路由配置应该如下:
app.UseEndpoints(endpoints =>
{
endpoints.MapAreaControllerRoute(
name: "AdminAreaRoute",
areaName: "Admin",
pattern: "admin/{controller:slugify=Dashboard}/{action:slugify=Index}/{id:slugify?}");
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller:slugify}/{action:slugify}/{id:slugify?}",
defaults: new { controller = "Home", action = "Index" });
});
Run Code Online (Sandbox Code Playgroud)
对于 ASP.NET Core >=3.0 Web API:
在类的ConfigureServices方法中Startup:
services.AddControllers(options =>
{
options.Conventions.Add(new RouteTokenTransformerConvention(new SlugifyParameterTransformer()));
});
Run Code Online (Sandbox Code Playgroud)
对于 ASP.NET Core >=3.0 Razor 页面:
在类的ConfigureServices方法中Startup:
services.AddRazorPages(options =>
{
options.Conventions.Add(new PageRouteTransformerConvention(new SlugifyParameterTransformer()));
});
Run Code Online (Sandbox Code Playgroud)
这是将/Employee/EmployeeDetails/1路由到/employee/employee-details/1
Oli*_*ver 13
这里的派对有点晚了但是..可以通过实现IControllerModelConvention来做到这一点.
public class DashedRoutingConvention : IControllerModelConvention
{
public void Apply(ControllerModel controller)
{
var hasRouteAttributes = controller.Selectors.Any(selector =>
selector.AttributeRouteModel != null);
if (hasRouteAttributes)
{
// This controller manually defined some routes, so treat this
// as an override and not apply the convention here.
return;
}
foreach (var controllerAction in controller.Actions)
{
foreach (var selector in controllerAction.Selectors.Where(x => x.AttributeRouteModel == null))
{
var template = new StringBuilder();
if (controllerAction.Controller.ControllerName != "Home")
{
template.Append(PascalToKebabCase(controller.ControllerName));
}
if (controllerAction.ActionName != "Index")
{
template.Append("/" + PascalToKebabCase(controllerAction.ActionName));
}
selector.AttributeRouteModel = new AttributeRouteModel()
{
Template = template.ToString()
};
}
}
}
public static string PascalToKebabCase(string value)
{
if (string.IsNullOrEmpty(value))
return value;
return Regex.Replace(
value,
"(?<!^)([A-Z][a-z]|(?<=[a-z])[A-Z])",
"-$1",
RegexOptions.Compiled)
.Trim()
.ToLower();
}
}
Run Code Online (Sandbox Code Playgroud)
然后在Startup.cs中注册它
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc(options => options.Conventions.Add(new DashedRoutingConvention()));
}
Run Code Online (Sandbox Code Playgroud)
可以在这里找到更多信息和示例https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/routing
我正在使用Asp.NetCore 2.0.0和Razor Pages(不需要显式控制器),所以所需要的只是:
启用小写网址:
services.AddRouting(options => options.LowercaseUrls = true);
创建一个名为的文件Dashboard-Settings.cshtml,结果路由成为/dashboard-settings
复制自 ASP.NET Core 3.0(与 2.2 相同)文档:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.Conventions.Add(new RouteTokenTransformerConvention(
new SlugifyParameterTransformer()));
});
}
public class SlugifyParameterTransformer : IOutboundParameterTransformer
{
public string TransformOutbound(object value)
{
if (value == null) { return null; }
// Slugify value
return Regex.Replace(value.ToString(), "([a-z])([A-Z])", "$1-$2").ToLower();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4536 次 |
| 最近记录: |