如何检查 uri 字符串是否有效

发布于 2024-10-15 04:00:05 字数 852 浏览 8 评论 0原文

如何检查 uri 字符串是否有效(可以将其提供给 Uri 构造函数)?

到目前为止,我只有以下内容,但出于明显的原因,我更喜欢一种不那么粗暴的方式:

    Boolean IsValidUri(String uri)
    {
        try
        {
            new Uri(uri);
            return true;
        }
        catch
        {
            return false;
        }
    }

我尝试了 Uri.IsWellFormedUriString 但它似乎并不喜欢您可以扔给构造函数的所有内容。例如:

String test = @"C:\File.txt";
Console.WriteLine("Uri.IsWellFormedUriString says: {0}", Uri.IsWellFormedUriString(test, UriKind.RelativeOrAbsolute));
Console.WriteLine("IsValidUri says: {0}", IsValidUri(test));

输出将是:

Uri.IsWellFormedUriString says: False
IsValidUri says: True

Update/Answer

Uri 构造函数默认使用绝对类型。当我尝试使用 Uri.TryCreate 和构造函数时,这导致了差异。如果您匹配构造函数和 TryCreate 的 UriKind,您确实会得到预期的结果。

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 less brute way:

    Boolean IsValidUri(String uri)
    {
        try
        {
            new Uri(uri);
            return true;
        }
        catch
        {
            return false;
        }
    }

I tried Uri.IsWellFormedUriString but it doesn't seem to like everything that you can throw at the constructor. For example:

String test = @"C:\File.txt";
Console.WriteLine("Uri.IsWellFormedUriString says: {0}", Uri.IsWellFormedUriString(test, UriKind.RelativeOrAbsolute));
Console.WriteLine("IsValidUri says: {0}", IsValidUri(test));

The output will be:

Uri.IsWellFormedUriString says: False
IsValidUri says: True

Update/Answer

The Uri constructor uses kind Absolute by default. This was causing a discrepancy when I tried using Uri.TryCreate and the constructor. You do get the expected outcome if you match the UriKind for both the constructor and TryCreate.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

回首观望 2024-10-22 04:00:05

格式良好的 URI 意味着符合某些 RFC。您的示例中的本地路径与这些不符。在 IsWellFormedUriString 文档。

该方法的错误结果并不意味着 Uri 类将无法解析输入。虽然 URI 输入可能不符合 RFC,但它仍然可以是有效的 URI。

更新:为了回答您的问题 - 正如 Uri 文档所示,有一个名为 TryCreate 它将完全尝试您想要的操作并返回 true 或 false(如果 true,则返回实际的 Uri 实例)。

A well-formed URI implies conformance with certain RFCs. The local path in your example is not conformant with these. Read more in the IsWellFormedUriString documentation.

A false result from that method does not imply that the Uri class will not be able to parse the input. While the URI input might not be RFC conformant, it still can be a valid URI.

Update: And to answer your question - as the Uri documentation shows, there is a static method called TryCreate that will attempt exactly what you want and return true or false (and the actual Uri instance if true).

此生挚爱伱 2024-10-22 04:00:05

由于接受的答案没有提供明确的示例,因此下面是一些在 C# 中验证 URI 的代码:

Uri outUri;

if (Uri.TryCreate("ThisIsAnInvalidAbsoluteURI", UriKind.Absolute, out outUri)
   && (outUri.Scheme == Uri.UriSchemeHttp || outUri.Scheme == Uri.UriSchemeHttps))
{
    //Do something with your validated Absolute URI...
}

Since the accepted answer doesn't provide an explicit example, here is some code to validate URIs in C#:

Uri outUri;

if (Uri.TryCreate("ThisIsAnInvalidAbsoluteURI", UriKind.Absolute, out outUri)
   && (outUri.Scheme == Uri.UriSchemeHttp || outUri.Scheme == Uri.UriSchemeHttps))
{
    //Do something with your validated Absolute URI...
}
木森分化 2024-10-22 04:00:05

假设我们只想支持绝对 URI 和 HTTP 请求,下面是一个可以完成您想要的功能的函数:

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;
}

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;
}
简美 2024-10-22 04:00:05

就我而言,我只想测试 uri,我不想减慢测试 uri 的应用程序的速度。

Boolean IsValidUri(String uri){
  return Uri.IsWellFormedUriString(uri, UriKind.Absolute);
}

In my case I just wanted to test the uri, I don't want to slow down the application testing the uri.

Boolean IsValidUri(String uri){
  return Uri.IsWellFormedUriString(uri, UriKind.Absolute);
}
影子是时光的心 2024-10-22 04:00:05

尝试一下:

private bool IsValidUrl(string address)
    {
        return Uri.IsWellFormedUriString(address, UriKind.RelativeOrAbsolute);
    }

Try it:

private bool IsValidUrl(string address)
    {
        return Uri.IsWellFormedUriString(address, UriKind.RelativeOrAbsolute);
    }
所谓喜欢 2024-10-22 04:00:05

在您的情况下, uri 参数是引用文件位置的绝对路径,因此根据方法的文档,它返回 false。请参阅

In your case the uri argument is an absolute path which refers to a file location, so as per the doc of the method it returns false. Refer to this

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文