您可以使用
UriBuilder
直接实现您想要的功能,它可以处理相对和绝对URI(请参见以下示例)。
同时,@icktoofay也提出了一个好建议:一定要在允许列表中包含子域名(如
www.google.com
),或者对
builder.Host
属性进行更多处理以获取实际域名。如果决定进行更多处理,请勿忘记带有复杂顶级域名(如
bbc.co.uk
)的URL。
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)
);
}
}
}
www
子域名。 - icktoofay