什麼喲你說的是一個slu。。您只需在您的博客類中添加一個屬性,以保存一些將構成URL一部分的唯一字符串值。例如:
[Index]
[StringLength(80)]
public string Slug { get; set; }
然後,在創建博客時,你可以手動指定值Slug
(使其在形式的場)或「slugifying」的博客中或某事的標題撰寫它。我用下面的字符串擴展:
public static string RemoveDiacritics(this string s)
{
s = s ?? string.Empty;
if (s.Length > 0)
{
char[] chars = new char[s.Length];
int charIndex = 0;
s = s.Normalize(NormalizationForm.FormD);
for (int i = 0; i < s.Length; i++)
{
char c = s[i];
if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
chars[charIndex++] = c;
}
return new string(chars, 0, charIndex).Normalize(NormalizationForm.FormC);
}
return s;
}
public static string Slugify(this string s, int maxLength = 80)
{
s = s ?? string.Empty;
//First to lower case
s = s.ToLowerInvariant().RemoveDiacritics();
//Replace spaces
s = Regex.Replace(s, @"\s", "-", RegexOptions.Compiled);
//Remove invalid chars
s = Regex.Replace(s, @"[^a-z0-9s\-_]", "", RegexOptions.Compiled);
//Trim dashes from end
s = s.Trim('-', '_');
//Replace double occurences of - or _
s = Regex.Replace(s, @"([\-_]){2,}", "$1", RegexOptions.Compiled);
while (s.Length > maxLength)
{
var pieces = s.Split('-');
pieces = pieces.Take(pieces.Count() - 1).ToArray();
s = string.Join("-", pieces);
}
return s;
}
然後,例如,你可以這樣做:
blog.Slug = blog.Title.Slugify();
但是您創建的蛞蝓,你會再使用URL參數去查查博客由:
public ActionResult GetBlog(string slug)
{
var blog = db.Blogs.SingleOrDefault(m => m.Slug == slug);
這就是爲什麼Slug
屬性上面綴[Index]
。這使EF在創建表/添加列時爲該列創建索引。出於性能原因,您打算查詢的任何列應該被編入索引。此外,您必須爲列定義一個設置長度,因爲NVARCHAR(MAX)(字符串的默認列類型)不能被索引。
感謝您的評論! –