I am creating new .NET MVC web apllication and to make it's url seo friendly i would like to create dynamic url's based on post title etc.
how can i do it in .NET MVC
Also i believe, i would have to change routing also using RouteConfig.cs
Any help would be appreciated, thanks
Hello, thank you for asking your question
I will clear all the things step by step :-
Helper
class for generating
seo friendly url//Pass your title as Name in this url, and get generated slug
public static string GenerateSlug(string Name)
{
string phrase = string.Format("{0}", Name);
string str = RemoveAccent(phrase).ToLower();
// invalid chars
str = Regex.Replace(str, @"[^a-z0-9\s-]", "");
// convert multiple spaces into one space
str = Regex.Replace(str, @"\s+", " ").Trim();
// cut and trim
str = str.Substring(0, str.Length <= 60 ? str.Length : 60).Trim();
str = Regex.Replace(str, @"\s", "-"); // hyphens
return str;
}
// About getEnocding https://msdn.microsoft.com/en-us/library/system.text.encodinginfo.getencoding(v=vs.110).aspx
private static string RemoveAccent(string text)
{
byte[] bytes = System.Text.Encoding.GetEncoding("Cyrillic").GetBytes(text);
return System.Text.Encoding.ASCII.GetString(bytes);
}
RouteConfig.cs
RouteConfig.cs
placed in App_Start
folder of your MVC application, now place this code
above Default Route routes.MapRoute(
name: "Test", //Route Name
url: "category/{generatedSlug}/{id}",// dynamic URL
defaults: new { controller = "Post", action = "PostDetailsAction", generatedSlug = UrlParameter.Optional,id=UrlParameter.Optional }
);
//action = method which generates post's data based on id from database
that's it, you are done :)
method RemoveAccent not have ?
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly