如何在创建友好URL时删除无效字符(即如何创建slug)?

Ant*_*ony 12 asp.net url-rewriting slug

说我有这个网页:http://ww.xyz.com/Product.aspx? CategoryId
= 1

如果CategoryId = 1的名称是"Dogs",我想将URL转换为如下内容:http:
//ww.xyz.com/Products/Dogs

问题是如果类别名称包含外来(或对于URL无效)字符.如果CategoryId = 2的名称是"Göraäldre",那么新网址应该是什么?

逻辑上它应该是:
http: //ww.xyz.com/Products/Göraäldre
但它不起作用.首先是因为空间(我可以很容易地用短划线取代)但是外国人物呢?在Asp.net中我可以使用URLEncode函数,它会给出类似这样的东西:
http://ww.xyz.com/Products/G%c3%b6ra+%c3%a4ldre
但是我不能说它比原来更好url(http://ww.xyz.com/Product.aspx?CategoryId=2)

理想情况下,我想生成这个,但我怎么能自动执行此操作(即将外来字符转换为'安全'url字符):http:
//ww.xyz.com/Products/Gora-aldre

Ant*_*ony 27

我想出了以下两种扩展方法(asp.net/C#):

     public static string RemoveAccent(this string txt)
    {
        byte[] bytes = System.Text.Encoding.GetEncoding("Cyrillic").GetBytes(txt);
        return System.Text.Encoding.ASCII.GetString(bytes);
    }

    public static string Slugify(this string phrase)
    {
        string str = phrase.RemoveAccent().ToLower();
        str = System.Text.RegularExpressions.Regex.Replace(str, @"[^a-z0-9\s-]", ""); // Remove all non valid chars          
        str = System.Text.RegularExpressions.Regex.Replace(str, @"\s+", " ").Trim(); // convert multiple spaces into one space  
        str = System.Text.RegularExpressions.Regex.Replace(str, @"\s", "-"); // //Replace spaces by dashes
        return str;
    }
Run Code Online (Sandbox Code Playgroud)

  • 在我发现这个之前,我写了一个充满if语句的巨大方法.好东西. (3认同)