c# - 一般如何在 MapRoute 方法中实现 URL 重写?

标签 c# url-rewriting seo asp.net-mvc-routing


我正在尝试将 URL 从 C# 的 Pascal 大小写重写为 SEO 友好的格式。
例如,我希望 /User/Home/MyJumbledPageName 看起来像这样:

/user/home/my-jumbled-page-name // lower-case, and words separated by dashes


这是我转换 URL 中每个“ token ”的方法:

public static string GetSEOFriendlyToken(string token)
{
    StringBuilder str = new StringBuilder();

    for (int i = 0, len = token.Length; i < len; i++)
    {
        if (i == 0)
        {
            // setting the first capital char to lower-case:
            str.Append(Char.ToLower(token[i]));
        }
        else if (Char.IsUpper(token[i]))
        {
            // setting any other capital char to lower-case, preceded by a dash:
            str.Append("-" + Char.ToLower(token[i]));
        }
        else
        {
            str.Append(token[i]);
        }
    }
    return str.ToString();
}


...并且在根目录中的 RouteConfig.cs 文件中,我映射了这些路由:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    // without this the first URL is blank:
    routes.MapRoute(
        name: "Default_Home",
        url: "index", // hard-coded?? it works...
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );

    routes.MapRoute(
        name: "Home",
        // the method calls here do not seem to have any effect:
        url: GetSEOFriendlyToken("{action}") + "/" + GetSEOFriendlyToken("{id}"),
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}


使用此代码,诸如 /AboutTheAuthor 这样的 URL 不会转换为我想要的内容,即 /about-the-author

看来我的方法调用被忽略了,这里发生了什么?实现这一点的传统方法是什么?

最佳答案

您必须定义自己的RouteBase类或子类Route

public class SeoFriendlyRoute : Route
{
    private readonly string[] _valuesToSeo;

    public SeoFriendlyRoute(string url, RouteValueDictionary defaults, IEnumerable<string> valuesToSeo, RouteValueDictionary constraints = null, RouteValueDictionary dataTokens = null, IRouteHandler routeHandler = null)
        : base(url, defaults, constraints ?? new RouteValueDictionary(), dataTokens ?? new RouteValueDictionary(), routeHandler ?? new MvcRouteHandler())
    {
        if (valuesToSeo == null) { throw new ArgumentNullException("valuesToSeo"); }
        _valuesToSeo = valuesToSeo.ToArray();
    }
    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        var routeData = base.GetRouteData(httpContext);
        if (routeData != null)
        {
            foreach (var key in _valuesToSeo)
            {
                if (routeData.Values.ContainsKey(key))
                {
                    routeData.Values[key] = GetActualValue((string)routeData.Values[key]);
                }
            }
        }
        return routeData;
    }
    public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
    {
        var seoFriendyValues = new RouteValueDictionary(values);
        foreach (var key in _valuesToSeo)
        {
            if (seoFriendyValues.ContainsKey(key))
            {
                seoFriendyValues[key] = GetSeoFriendlyValue((string)seoFriendyValues[key]);
            }
        }
        return base.GetVirtualPath(requestContext, seoFriendyValues);
    }

    private string GetSeoFriendlyValue(string actualValue)
    {
        //your method
        StringBuilder str = new StringBuilder();
        for (int i = 0, len = actualValue.Length; i < len; i++)
        {
            if (i == 0)
            {
                str.Append(Char.ToLower(actualValue[i]));
            }
            else if (Char.IsUpper(actualValue[i]))
            {
                str.Append("-" + Char.ToLower(actualValue[i]));
            }
            else
            {
                str.Append(actualValue[i]);
            }
        }
        return str.ToString();
    }

    private static string GetActualValue(string seoFriendlyValue)
    {
        //action name is not case sensitive
        //one limitation is the dash can be anywhere but the action will still be resolved
        // /my-jumbled-page-name is same as /myjumbled-pagename
        return seoFriendlyValue.Replace("-", string.Empty); 
    }
}

使用

routes.Add("Default", new SeoFriendlyRoute(
    url: "{controller}/{action}/{id}",
    valuesToSeo: new string[] { "action", "controller" },
    defaults: new RouteValueDictionary(new { controller = "Home", action = "Index", id = UrlParameter.Optional }))
);

关于c# - 一般如何在 MapRoute 方法中实现 URL 重写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20651661/

相关文章:

nginx - 防止NGINX移除端口

c# - 如何创建单个 Web 应用程序作为许多公司的子域

redirect - URL 更改的高流量页面

WebSphere Portal 中的 SEO(页面标题)

c# - 这个 Font 对象什么时候被释放?

c# - ComboBox 中只允许不同的值

c# - 数组中的任务——只有最后一个运行

c# - 墓碑工作正常,但我的应用程序需要它吗?

c# - .NET URI : How can I change ONE part of a URI?

javascript - SEO:如何索引来自客户端 api 请求的数据