【问题标题】:CheckSchemeName fail on url with multiple prefixCheckSchemeName 在具有多个前缀的 url 上失败
【发布时间】:2019-06-06 12:41:39
【问题描述】:

我有这个网址:turnerstadium.co.il,我正在尝试检查scheme 是否正确,所以我做了:

if (!Uri.CheckSchemeName(link))
{
   link = "http://" + link;
}

问题是CheckSchemeName 返回true,所以当我这样做时:

var url = new Uri(link);

我明白了:

无效的 URI:无法确定 URI 的格式

我该如何解决这个问题?

【问题讨论】:

标签: c#


【解决方案1】:

检查 UriBuilder:https://docs.microsoft.com/en-us/dotnet/api/system.uribuilder?view=netframework-4.7.2

如果方案不存在,它有构造函数来添加方案。

var url = new UriBuilder("siteUrl.com").Uri.ToString();

这将返回“http://siteUrl.com

【讨论】:

    【解决方案2】:

    这是 CheckSchemeName 方法的代码。

    public static bool CheckSchemeName(string schemeName)
    {
      if (schemeName == null || schemeName.Length == 0 || !Uri.IsAsciiLetter(schemeName[0]))
        return false;
      for (int index = schemeName.Length - 1; index > 0; --index)
      {
        if (!Uri.IsAsciiLetterOrDigit(schemeName[index]) && schemeName[index] != '+' && (schemeName[index] != '-' && schemeName[index] != '.'))
          return false;
      }
      return true;
    }
    

    来自Uri.CheckSchemeName的备注部分:

    方案名称必须以字母开头,并且只能包含 字母、数字和字符“.”、“+”或“-”。

    如你所见,这个方法只检查你传递的字符串是否满足这些要求。

    如果您只想检查字符串是否以“http://”开头并附加它以防万一它不存在,可能的解决方案之一是:

      if (!link.StartsWith("http://"))
      {
        link = "http://" + link;
      }
    

    否则我建议阅读this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多