如果我像这样使用 UriBuilder
创建一个 Uri
:
var rootUrl = new UriBuilder("http", "example.com", 50000).Uri;
然后 rootUrl
的 AbsoluteUri
总是包含一个尾部斜杠,如下所示:
http://example.com:50000/
我想要的是创建一个没有尾部斜线的 Uri
对象,但这似乎是不可能的。
我的解决方法是将它存储为字符串,然后做一些丑陋的事情:
var rootUrl = new UriBuilder("http", "example.com", 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 中不是必需的,但它是请求的绝对 URI 的规范表示的一部分 in HTTP :
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
对象上不可配置。 Web 浏览器和许多 HTTP 客户端在发送具有空路径的 URL 请求时执行相同的重写。
如果我们想在内部将我们的 URL 表示为 Uri
对象,而不是字符串,我们可以创建一个 extension method格式化没有尾部斜杠的 URL,它将此表示逻辑抽象在一个位置,而不是每次我们需要输出 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", "example.com", 50000).Uri;
Console.WriteLine(rootUrl.ToRootHttpUriString()); // "http://example.com:50000"
关于c# - 没有尾部斜杠的基本 Uri,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46968185/