Search code examples
.netasp.netasp.net-mvcvalidationurl

Is there a URL validator on .Net?


Is there a method to validate URLs in .Net, ASP.Net, or ASP.Net MVC?


Solution

  • You can use the Uri.TryCreate to validate an URL:

    public bool IsValidUri(string uri)
    {
        Uri validatedUri;
        return Uri.TryCreate(uri, UriKind.RelativeOrAbsolute, out validatedUri);
    }
    

    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 inside TryCreate, it uses a custom parser which should not throw.