我最近意识到,与URL和URI相关的.NET API在实现基本功能(至少是容易实现的)方面经常不够完善,包括:从相对路径生成FQDN URL,强制使用https或返回http,获取站点的根目录,正确组合相对URL等等。
是否有任何替代库已将所有这些类型的功能放入简单可靠的项目中?
是否有任何替代库已将所有这些类型的功能放入简单可靠的项目中?
我确实发现自己在.NET中经常重复编写相同的URI操作代码,但我并不认为你提到的情况是它缺乏的地方。
从相对Uri获取完整的URI:
new Uri(base, relative) // (works whether relative is a string or a Uri).
获取实际的FQDN:
string host = uri.Host;
string fqdn = hostEndsWith(".") ? host : host + ".";
强制使用https或返回http:
UriBuilder toHttp = new UriBuilder(someUri);
toHttp.Scheme = "http";
toHttp.Port = 80;
return toHttp.Uri;
UriBuilder toHttps = new UriBuilder(someUri);
toHttps.Scheme = "https";
toHttps.Port = 443;
return toHttps.Uri;
获取站点根目录:
new Uri(startingUri, "/");
合理地组合相对URL:
new Uri(baseUri, relUri); // We had this one already.
只有两种情况需要调用多个方法,其中获取FQDN相对比较难以理解(除非你想要以点结尾的FQDN而不是绝对URI,这种情况下我们又回到了单个方法调用)。
虽然有一种单独的方法可以实现HTTPS/HTTP切换,但它实际上更加繁琐,因为它调用了Uri对象的几个属性。我可以接受需要几行代码来完成此切换。
仍然,为了提供新的API,只需提供:
public static Uri SetHttpPrivacy(this Uri uri, bool privacy)
{
UriBuilder ub = new UriBuilder(uri);
if(privacy)
{
ub.Scheme = "https";
ub.Port = 443;
}
else
{
ub.Scheme = "http";
ub.Port = 80;
}
return ub.Uri;
}
我真的看不出来API在其他情况下可能会更简洁。
public static Uri SecureIfRemote(this Uri uri){
if(!System.Web.HttpContext.Current.Request.IsSecureConnection &&
!System.Web.HttpContext.Current.Request.IsLocal){
return new Uri......(build secure uri here)
}
return uri;
}
public static NameValueCollection ParseQueryString(Uri uri){
return uri.Query.ParseQueryString();
}
public static NameValueCollection ParseQueryString(this string s)
{
//return
return HttpUtility.ParseQueryString(s);
}