首页 > 解决方案 > 无法在 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;
}

标签: asp.net-coreroutesasp.net-core-mvc

解决方案


首先,您的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


推荐阅读