Is there a method to validate URLs in .Net, ASP.Net, or ASP.Net MVC?
相关问题
- Carriage Return (ASCII chr 13) is missing from tex
- MVC-Routing,Why i can not ignore defaults,The matc
- Generic Generics in Managed C++
- How to store image outside of the website's ro
- How to Debug/Register a Permanent WMI Event Which
A faster way (probably) than using try/catch functionality would be to use Regex. If you had to validate 1000s of URLs catching the exception multiple times would be slow.
Here's a link to sample Regex- use Google to find more.
You can use Uri.IsWellFormedUriString, no need to create your own function for that:
Where uriKind can be:
For more info see: http://msdn.microsoft.com/en-us/library/system.uri.iswellformeduristring.aspx
The answers provided thusfar do not check for a scheme, allowing all kinds of unwanted input, which could make you vulnerable for javascript injection (see the comment of TheCloudlessSky).
An URI is just a unique identification of a object. "C:\Test" is a valid URI.
In my project I used the following code:
Define which schemes you will allow and change the code accordingly.
You can use the
Uri.TryCreate
to validate an URL:The comments suggest that
TryCreate
just moves the exception handling one level down. However, I checked the source code and found that this is not the case. There is no try/catch insideTryCreate
, it uses a custom parser which should not throw.