Determine if Absolute or Relative URL

2019-01-23 10:08发布

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

标签: c# parsing url
3条回答
时光不老,我们不散
2楼-- · 2019-01-23 10:58

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

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-01-23 11:01
bool IsAbsoluteUrl(string url)
{
    Uri result;
    return Uri.TryCreate(url, UriKind.Absolute, out result);
}
查看更多
放荡不羁爱自由
4楼-- · 2019-01-23 11:06

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)
            );
        }
    }
}
查看更多
登录 后发表回答