c# – 没有尾部斜线的基础Uri

如果我使用UriBuilder创建一个Uri,如下所示:
var rootUrl = new UriBuilder("http","example.com",50000).Uri;

那么rootUrl的AbsoluteUri总是包含一个这样的尾部斜杠:

http://example.com:50000/

我想要的是创建一个没有斜杠的Uri对象,但似乎不可能.

我的解决方法是将其存储为字符串,并做一些丑陋的事情:

var rootUrl = new UriBuilder("http",50000).Uri.ToString().TrimEnd('/');

我听说有人说没有尾随斜线,Uri无效.我不认为这是真的.我查看了RFC 3986,并在3.2.2节中说:

If a URI contains an authority component,then the path component
must either be empty or begin with a slash (“/”) character.

它并没有说尾随斜线必须在那里.

解决方法

任意URI中不需要尾部斜杠,但它是请求 in HTTP的绝对URI的规范表示的一部分:

Note that the absolute path cannot be empty; if none is present in the original URI,it MUST be given as “/” (the server root).

为了遵守the spec,Uri类在表单中输出一个带有斜杠的URI:

In general,a URI that uses the generic Syntax for authority with an empty path should be normalized to a path of “/”.

在.NET中的Uri对象上无法配置此行为.在发送具有空路径的URL请求时,Web浏览器和许多HTTP客户端执行相同的重写.

如果我们想在内部将URL表示为Uri对象而不是字符串,我们可以创建一个extension method格式化URL而不使用尾部斜杠,它将此表示逻辑抽象在一个位置,而不是每次我们需要输出时将其复制显示的网址:

namespace Example.App.CustomExtensions 
{
    public static class UriExtensions 
    {
        public static string ToRootHttpUriString(this Uri uri) 
        {
            if (!uri.IsHttp()) 
            {
                throw new InvalidOperationException(...);
            }

            return uri.Scheme + "://" + uri.Authority;
        }

        public static bool IsHttp(this Uri uri) 
        {
            return uri.Scheme == "http" || uri.Scheme == "https";
        }
    }
}

然后:

using Example.App.CustomExtensions;
...

var rootUrl = new UriBuilder("http",50000).Uri; 
Console.WriteLine(rootUrl.ToRootHttpUriString()); // "http://example.com:50000"

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...