gpt4 book ai didi

asp.net-core - 约束引用 'slugify' 无法解析为类型

转载 作者:行者123 更新时间:2023-12-01 17:15:46 31 4
gpt4 key购买 nike

ASP.NET Core 2.2 引入了一个使用 Parameter transformer 来 slugifying 路由 url 的选项如下:

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 Core Documentation说我必须使用 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])", "$1-$2").ToLower();
}
}

谢谢。

关于asp.net-core - 约束引用 'slugify' 无法解析为类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52922418/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com