Should I store spaces in my URLs in the database? If so, how do you encode it when you put them in <a href= "https://stackoverflow.com/..." rel="nofollow noreferrer">?
On my blog, I store URIs on objects so that they are configured (and friendly). They might initially contain spaces (for example, "/tags/ASP.NET MVC"), but a W3C check says that spaces are not allowed.
The class System.Uriaccepts spaces and seems to encode them as I want (for example. /tags/ASP.NET MVCBecomes /tags/ASP.NET%20MVC), but I don't want to create Urijust to remove it, it feels dirty!
Note. None of Html.Encode, Html.AttributeEncodeand Url.Encodedoes not encode "/tags/ASP.NET MVC"to "/tags/ASP.NET%20MVC".
Edit: I edited part DataTypeof my question, as it turns out that DataType does not provide direct verification, and there is no built-in URI verification. I found some additional validators at dataannotationsextensions.org , but it only supports absolute URIs and it looks like spaces that can also be valid there.
, UrlPathEncode , , .
URL-, UrlEncode() UrlPathEncode(). . UrlEncode() (+). UrlPathEncode() "%20", .
EDIT: javascript encodeURI %20 +. Microsoft.JScript GlobalObject.encodeURI. , , :
URI URL- - , URL- URI. , URL- URI.
URL W3C, HttpUtility.UrlPathEncode(string). , .
URL- , , . URI , , URL-, , .
EDIT:
, "" , %2f /:
var path = "/tags/ASP.NET MVC";
var url = HttpUtility.UrlPathEncode(path).Replace("%2f", "/");
I asked this similar question a while ago. The short answer was to replace the spaces with “-” and then back off again. This is the source I used:
private static string EncodeTitleInternal(string title)
{
if (string.IsNullOrEmpty(title))
return title;
// Search engine friendly slug routine with help from http://www.intrepidstudios.com/blog/2009/2/10/function-to-generate-a-url-friendly-string.aspx
// remove invalid characters
title = Regex.Replace(title, @"[^\w\d\s-]", ""); // this is unicode safe, but may need to revert back to 'a-zA-Z0-9', need to check spec
// convert multiple spaces/hyphens into one space
title = Regex.Replace(title, @"[\s-]+", " ").Trim();
// If it over 30 chars, take the first 30.
title = title.Substring(0, title.Length <= 75 ? title.Length : 75).Trim();
// hyphenate spaces
title = Regex.Replace(title, @"\s", "-");
return title;
}