In ASP. in net mvc, URL Routing is a good way to standardize URLs. however, sometimes you may need to format the specified string into a normal and secure URL. we all know that generally, domain name registration requires only numbers. the information in the database is often used as a part of the Url. For example, when the author page is located, the author's name is often included.
Assume that the author is named tu zhi. the URL of the author information page is assumed as follows: <a href = "http://www.cnblogs.com/tu zhi"> rabbit paper </a> where tu zhi is the author name obtained from the data.
If we request this link, we find that the address after the jump is like this: http://www.cnblogs.com/tu%20zhi so the URL will appear very not beautiful, it also looks irregular. our goal is to convert it into a http://www.cnblogs.com/tu-zhi. If you say it's okay? I think % 20 is better, so when the author name isTu & zhiWhen? If you are interested, try it. If you don't talk much about it, go to the topic.
The processing method for this string is very simple, and one method is sufficient:
/// <Summary>
/// Convert to url
/// </Summary>
/// <Param name = "text"> text </param>
/// <Returns> url character </returns>
Public static string ToUrlName (this string text)
{
If (text = null)
Throw new Exception ("Can't Url convert a null string."); // cannot be converted if it is null
Var result = text. Trim (). Replace ("", "-"); // convert
Var replacer = new Regex (@ "[^ \ w \-]", RegexOptions. Compiled); // Regular Expression
Result = replacer. Replace (result, ""). ToLower ();
Return result;
}
You can do this when calling:
string author = Strings.ToUrlName("tu zhi");
Now, this article is over. I hope to help you a little bit. The next article will introduce some custom HtmlHelper extensions. If you are interested, continue to follow rabbit paper articles.