简体   繁体   English

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

[英]How to check that a uri string is valid

How do you check that a uri string is valid (that you can feed it to the Uri constructor)?您如何检查 uri 字符串是否有效(您可以将其提供给 Uri 构造函数)?

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.我试过 Uri.IsWellFormedUriString 但它似乎并不喜欢你可以扔给构造函数的所有东西。 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. Uri 构造函数默认使用绝对类型。 This was causing a discrepancy when I tried using Uri.TryCreate and the constructor.当我尝试使用 Uri.TryCreate 和构造函数时,这导致了差异。 You do get the expected outcome if you match the UriKind for both the constructor and TryCreate.如果您匹配构造函数和 TryCreate 的 UriKind,您确实会得到预期的结果。

A well-formed URI implies conformance with certain RFCs.格式正确的 URI 意味着符合某些 RFC。 The local path in your example is not conformant with these.您示例中的本地路径与这些不符。 Read more in the IsWellFormedUriString documentation.IsWellFormedUriString文档中阅读更多信息。

A false result from that method does not imply that the Uri class will not be able to parse the input.该方法的错误结果并不意味着Uri类将无法解析输入。 While the URI input might not be RFC conformant, it still can be a valid URI.虽然 URI 输入可能不符合 RFC,但它仍然可以是有效的 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).更新:并回答您的问题 - 正如 Uri 文档所示,有一个名为TryCreate的静态方法将尝试您想要的内容并返回 true 或 false(如果为 true,则返回实际的Uri实例)。

Since the accepted answer doesn't provide an explicit example, here is some code to validate URIs in C#:由于接受的答案没有提供一个明确的例子,这里有一些代码来验证 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...
}

Assuming we only want to support absolute URI and HTTP requests, here is a function that does what you want:假设我们只想支持绝对 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;
}

In my case I just wanted to test the uri, I don't want to slow down the application testing the uri.在我的情况下,我只想测试 uri,我不想减慢测试 uri 的应用程序的速度。

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

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.在您的情况下,uri 参数是一个绝对路径,它指的是文件位置,因此根据该方法的文档,它返回 false。 Refer to this参考这个

Try it:试试看:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM