加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 18:36:31 所属栏目:百科 来源:网络整理
导读:如果我使用UriBuilder创建一个Uri,如下所示: var rootUrl = new UriBuilder("http","example.com",50000).Uri; 那么rootUrl的AbsoluteUri总是包含一个这样的尾部斜杠: http://example.com:50000/ 我想要的是创建一个没有斜杠的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"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读