How to dynamically create urls/links like: www.restaurant.com/restaurant/restaurant-name-without-some-characters-like-space-coma-etc/132
what are the keywords i can use to google some articles on this topic? (how to genererate and handle this kind of urls inside asp.net mvc)
There are some questions: How to generate links? (store slugs in db?) Redirect or not if slug isn't canonical?
edit: apparently they are called slugs
The AddHeader method adds a new HTTP header and a value to the HTTP response. Note: Once a header has been added, it cannot be removed.
URL rewriting is the process of intercepting an incoming Web request and redirecting the request to a different resource. When performing URL rewriting, typically the URL being requested is checked and, based on its value, the request is redirected to a different URL.
You have to use something as follows.
Routes.MapRoute(
"Post",
"posts/{id}/{*title}",
new { controller = "Posts", action = "view" }
);
And a simple extension method:
public static class UrlExtensions
{
public static string ResolveSubjectForUrl(this HtmlHelper source, string subject)
{
return Regex.Replace(Regex.Replace(subject, "[^\\w]", "-"), "[-]{2,}", "-");
}
}
I've always stored slugs in the database alongside whatever entity would be referenced by them. So for a blog post, you would have a "slug" field in the "posts" table.
To handle it in ASP.Net MVC is easy - you just use a regular route that would capture the slug in a parameter (possibly even just using {id}), and then your controller would look up the slug in the database, load the entity, and display it as normal.
Although you can use a simple RegEx to replace spaces and whatnot to generate your slugs, in reality this breaks down pretty quickly. You need to consider all kinds of characters that may appear in your titles. Michael Kaplan's blog has been linked to heavily for this exact purpose; he's shared a function that will strip diacritical marks from strings.
So, your "generate slug" algorithm should generally take the form of:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With