Add scheme to URL if needed

后端 未结 5 1925
耶瑟儿~
耶瑟儿~ 2020-12-08 08:49

To create a Uri from a string you can do this:

Uri u = new Uri(\"example.com\");

But the problem is if the string (like the one above) does

5条回答
  •  醉话见心
    2020-12-08 09:34

    If you just want to add the scheme, without validating the URL, the fastest/easiest way is to use string lookups, eg:

    string url = "mydomain.com";
    if (!url.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) url = "http://" + url;
    

    A better approach would be to use Uri to also validate the URL using the TryCreate method:

    string url = "mydomain.com";
    Uri uri;
    if ((Uri.TryCreate(url, UriKind.Absolute, out uri) || Uri.TryCreate("http://" + url, UriKind.Absolute, out uri)) &&
        (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps))
    {
        // Use validated URI here
    }
    

    As @JanDavidNarkiewicz pointed out in the comments, validating the Scheme is necessary to guard against invalid schemes when a port is specified without scheme, e.g. mydomain.com:80.

提交回复
热议问题