约束引用 'slugify' 无法解析为类型
The constraint reference 'slugify' could not be resolved to a type
ASP.NET Core 2.2 引入了使用 Parameter transformer 对路由 url 进行 slugifying 的选项,如下所示:
routes.MapRoute(
name: "default",
template: "{controller=Home:slugify}/{action=Index:slugify}/{id?}");
我做过同样的事情如下:
routes.MapRoute(
name: "default",
template: "{controller:slugify}/{action:slugify}/{id?}",
defaults: new { controller = "Home", action = "Index" });
我在ConfigureServices
方法中的路由配置如下:
services.AddRouting(option =>
{
option.LowercaseUrls = true;
});
但出现以下错误:
InvalidOperationException: The constraint reference 'slugify' could not be resolved to a type. Register the constraint type with 'Microsoft.AspNetCore.Routing.RouteOptions.ConstraintMap'.
和
RouteCreationException: An error occurred while creating the route with name 'default' and template '{controller:slugify}/{action:slugify}/{id?}'.
可能是我还遗漏了什么!请帮忙!
作为 ASP.NET 核心 Documentation says I have to configure Parameter transformer
using ConstraintMap。所以我做了如下并且有效:
ConfigureServices
方法中的路由配置应该如下:
services.AddRouting(option =>
{
option.ConstraintMap["slugify"] = typeof(SlugifyParameterTransformer);
option.LowercaseUrls = true;
});
则SlugifyParameterTransformer
如下:
public class SlugifyParameterTransformer : IOutboundParameterTransformer
{
public string TransformOutbound(object value)
{
// Slugify value
return value == null ? null : Regex.Replace(value.ToString(), "([a-z])([A-Z])", "-").ToLower();
}
}
谢谢。
ASP.NET Core 2.2 引入了使用 Parameter transformer 对路由 url 进行 slugifying 的选项,如下所示:
routes.MapRoute(
name: "default",
template: "{controller=Home:slugify}/{action=Index:slugify}/{id?}");
我做过同样的事情如下:
routes.MapRoute(
name: "default",
template: "{controller:slugify}/{action:slugify}/{id?}",
defaults: new { controller = "Home", action = "Index" });
我在ConfigureServices
方法中的路由配置如下:
services.AddRouting(option =>
{
option.LowercaseUrls = true;
});
但出现以下错误:
InvalidOperationException: The constraint reference 'slugify' could not be resolved to a type. Register the constraint type with 'Microsoft.AspNetCore.Routing.RouteOptions.ConstraintMap'.
和
RouteCreationException: An error occurred while creating the route with name 'default' and template '{controller:slugify}/{action:slugify}/{id?}'.
可能是我还遗漏了什么!请帮忙!
作为 ASP.NET 核心 Documentation says I have to configure Parameter transformer
using ConstraintMap。所以我做了如下并且有效:
ConfigureServices
方法中的路由配置应该如下:
services.AddRouting(option =>
{
option.ConstraintMap["slugify"] = typeof(SlugifyParameterTransformer);
option.LowercaseUrls = true;
});
则SlugifyParameterTransformer
如下:
public class SlugifyParameterTransformer : IOutboundParameterTransformer
{
public string TransformOutbound(object value)
{
// Slugify value
return value == null ? null : Regex.Replace(value.ToString(), "([a-z])([A-Z])", "-").ToLower();
}
}
谢谢。