如果需要,将方案添加到URL

Max*_*lli 62 .net c# uri

要从字符串创建Uri,您可以执行以下操作:

Uri u = new Uri("example.com");
Run Code Online (Sandbox Code Playgroud)

但问题是如果字符串(如上所述)不包含协议,您将获得异常:" Invalid URI: The format of the URI could not be determined."

为避免异常,您应该确保字符串包含协议,如下所示:

Uri u = new Uri("http://example.com");
Run Code Online (Sandbox Code Playgroud)

但是如果你把url作为输入,如果它丢失了,你如何添加协议呢?
我的意思是除了一些IndexOf/Substring操作?

优雅而快速的东西?

as-*_*cii 125

你也可以使用UriBuilder:

public static Uri GetUri(this string s)
{
    return new UriBuilder(s).Uri;
}
Run Code Online (Sandbox Code Playgroud)

来自MSDN的评论:

此构造函数初始化UriBuilder类的新实例,其中包含uri中指定的Fragment,Host,Path,Port,Query,Scheme和Uri属性.

如果uri未指定方案,则方案默认为"http:".

  • 小心使用:使用像`stackoverflow.com:80`这样的端口输入没有错误,但被解释为`Scheme:stackoverflow.com`,`Path:80`:`Port:-1`.不完全符合预期...... (17认同)
  • 这表示当您尝试使用protocall-less网址时无法解析主机名,例如"//domain.com" (3认同)

Ron*_*ald 7

如果您只想添加方案而不验证URL,最快/最简单的方法是使用字符串查找,例如:

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

更好的方法是Uri使用以下TryCreate方法验证URL :

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
}
Run Code Online (Sandbox Code Playgroud)

正如@JanDavidNarkiewicz在评论中指出的那样,Scheme当没有方案指定端口时,验证是必要的,以防止无效方案,例如mydomain.com:80.