ASP. net mvc format a string into a URL

Source: Internet
Author: User
Tags domain name registration

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.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.