How to check that a uri string is valid

后端 未结 5 1717
轻奢々
轻奢々 2020-12-01 08:32

How do you check that a uri string is valid (that you can feed it to the Uri constructor)?

So far I only have the following but for obvious reasons I\'d prefer a les

5条回答
  •  Happy的楠姐
    2020-12-01 09:16

    Assuming we only want to support absolute URI and HTTP requests, here is a function that does what you want:

    public static bool IsValidURI(string uri)
    {
        if (!Uri.IsWellFormedUriString(uri, UriKind.Absolute))
            return false;
        Uri tmp;
        if (!Uri.TryCreate(uri, UriKind.Absolute, out tmp))
            return false;
        return tmp.Scheme == Uri.UriSchemeHttp || tmp.Scheme == Uri.UriSchemeHttps;
    }
    

提交回复
热议问题