开发者

Determine if Absolute or Relative URL

I have a relative or absolute url in a string. I first need to know whether it is absolute or relative. How do I do this? I then want to determine if the domain of the url i开发者_如何学JAVAs in an allow list.

Here is my allow list, as an example:

string[] Allowed =
{
   "google.com",
   "yahoo.com",
   "espn.com"
}

Once I know whether its relative or absolute, its fairly simple I think:

if (Url.IsAbsolute)
{
    if (!Url.Contains("://"))
        Url = "http://" + Url;

    return Allowed.Contains(new Uri(Url).Host);
}
else //Is Relative
{
    return true;
}


bool IsAbsoluteUrl(string url)
{
    Uri result;
    return Uri.TryCreate(url, UriKind.Absolute, out result);
}


For some reason a couple of good answers were deleted by their owners:

Via @Chamika Sandamal

Uri.IsWellFormedUriString(url, UriKind.Absolute)

and

Uri.IsWellFormedUriString(url, UriKind.Relative)

The UriParser and implementations via @Marcelo Cantos


You can achieve what you want more directly with UriBuilder which can handle both relative and absolute URIs (see example below).

@icktoofay makes a good point as well: be sure to either include subdomains (like www.google.com) in your allowed list or do more processing on the builder.Host property to get the actual domain. If you do decide to do more processing, don't forget about URLs with complex TLDs like bbc.co.uk.

using System;
using System.Linq;
using System.Diagnostics;

namespace UriTest
{
    class Program
    {
        static bool IsAllowed(string uri, string[] allowedHosts)
        {
            UriBuilder builder = new UriBuilder(uri);
            return allowedHosts.Contains(builder.Host, StringComparer.OrdinalIgnoreCase);
        }

        static void Main(string[] args)
        {
            string[] allowedHosts =
            {
                "google.com",
                "yahoo.com",
                "espn.com"
            };

            // All true
            Debug.Assert(
                IsAllowed("google.com", allowedHosts) &&
                IsAllowed("google.com/bar", allowedHosts) &&
                IsAllowed("http://google.com/", allowedHosts) &&
                IsAllowed("http://google.com/foo/bar", allowedHosts) &&
                IsAllowed("http://google.com/foo/page.html?bar=baz", allowedHosts)
            );

            // All false
            Debug.Assert(
                !IsAllowed("foo.com", allowedHosts) &&
                !IsAllowed("foo.com/bar", allowedHosts) &&
                !IsAllowed("http://foo.com/", allowedHosts) &&
                !IsAllowed("http://foo.com/foo/bar", allowedHosts) &&
                !IsAllowed("http://foo.com/foo/page.html?bar=baz", allowedHosts)
            );
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜