In my blog, I store URIs on entities to allow them be customised (and friendly). Originally, they could contain spaces (eg. "/tags/ASP.NET MVC"), but the W3C validation says spaces are not valid.
The System.Uri
class takes spaces, and seems to encode them as I want (eg. /tags/ASP.NET MVC
becomes /tags/ASP.NET%20MVC
), but I don't want to create a Uri
just to throw it away, this feels dirty!
Note: None of Html.Encode
, Html.AttributeEncode
and Url.Encode
will encode "/tags/ASP.NET MVC"
to "/tags/ASP.NET%20MVC"
.
Edit: I edited the DataType
part out of my question as it turns out DataType does not directly provide any validation, and there's no built-in URI validation. I found some extra validators at dataannotationsextensions.org but it only supports absolute URIs and it looks like spaces my be valid there too.
It seems that the only sensible thing to do is not allow spaces in URLs. Support for encoding them correctly seems flaky in .NET :(
I'm going to instead replace spaces with a dash when I auto-generate them, and validate they only contain certain characters (alphanumeric, dots, dashes, slashes).
I think the best way to use them would be to store %20 in the DB, as the space is "unsafe" and it seems non-trivial to then encode them in a way that will pass the W3C validator in .NET.
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