Is there a URL validator on .Net?

后端 未结 5 589
失恋的感觉
失恋的感觉 2020-12-28 12:37

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

5条回答
  •  余生分开走
    2020-12-28 12:59

    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:

    /// 
    /// Validates a URL.
    /// 
    /// 
    /// 
    private bool ValidateUrl(string url)
    {
        Uri validatedUri;
    
        if (Uri.TryCreate(url, UriKind.Absolute, out Uri validatedUri)) //.NET URI validation.
        {
            //If true: validatedUri contains a valid Uri. Check for the scheme in addition.
            return (validatedUri.Scheme == Uri.UriSchemeHttp || validatedUri.Scheme == Uri.UriSchemeHttps);
        }
        return false;
    }
    

    Define which schemes you will allow and change the code accordingly.

提交回复
热议问题