asp.net-core - 无法在 asp.net core mvc 中处理路由的 url
问题描述
我正在尝试处理一些路由的 url。我关注了这篇文章,但我无法复制结果。在 TransformOutbound() 中设置断点时,它永远不会命中,所以我猜变压器永远不会因为某种原因被调用。
SlugifyParameterTransformer:
public class SlugifyParameterTransformer : IOutboundParameterTransformer
{
public string TransformOutbound(object value)
{
string result = default;
if (!value.IsNull())
{
result = Regex.Replace(value.ToString(), "([a-z])([A-Z])", "$1-$2").ToLower();
}
return result;
}
}
启动:
public void ConfigureServices(IServiceCollection services)
{
services.AddLCAssets(opt =>
{
opt.Conventions.Add(new RouteTokenTransformerConvention(new SlugifyParameterTransformer()));
});
}
添加LCAssets:
public static IServiceCollection AddLCAssets(this IServiceCollection services, Action<MvcOptions> options = default)
{
if (options != default)
{
services.AddMvc(options)
.SetCompatibilityVersion(Const.DefaultCompatibilityVersion);
}
else
{
services.AddMvc()
.SetCompatibilityVersion(Const.DefaultCompatibilityVersion);
}
return services;
}
解决方案
首先,您的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();
}
}
然后在Startup.ConfigureServices
如下:
services.AddRouting(option =>
{
option.ConstraintMap["slugify"] = typeof(SlugifyParameterTransformer);
option.LowercaseUrls = true;
});
那么你的路由配置Startup.Configure
应该如下:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller:slugify}/{action:slugify}/{id?}",
defaults: new { controller = "Home", action = "Index" });
});
以上设置将使/Employee/EmployeeDetails/1
路由到/employee/employee-details/1
推荐阅读
- flutter - 如何在更好的播放器中获取当前位置并在应用关闭时保存它
- signal-processing - 有没有办法在不使用互联网的情况下通过传感器与智能手机远程通信?
- keycloak - 使用 keycloak 的 admin-cli 进行部分导出时,如何包含客户端和角色/组?(单次调用,如 UI)
- django - 将表达式与 CHECK 约束中的常量进行比较
- javascript - 如何在javascript中将字符串转换为对象
- java - java 可执行文件到底是什么,它有什么作用,我在哪里可以找到它的源代码?
- android - 即使在设置环境后,studio64.exe 也无法启动
- ssms - SSMS 导入/导出数据向导到 Azure Synapse 问题
- java - 如何在 Java 中导出 Google analitycs 数据?
- c - 为什么我的 tcp syn 消息没有得到 tcp syn ack 所以我无法连接到服务器