微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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"

原文地址:https://www.jb51.cc/csharp/99049.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐