.NET Microsoft.AspNetCore.Http.Extensions UriHelper.GetDisplayUrl 返回无效的 URI

Tom*_*Tom 2 .net c# http .net-core

我是 .NET 框架的新手,并且在界面方面遇到问题Microsoft.AspNetCore.Http.HttpRequest。我正在尝试使用GetDisplayUri扩展,但它返回无效的 URI。后来我将 URI 传递给System.Uri.CreateThis()并抛出以下异常:

System.UriFormatException: Invalid URI: The format of the URI could not be determined.
Run Code Online (Sandbox Code Playgroud)

该GetDisplayUri方法应该根据 中的字段创建一个 URL HttpRequest,但我无法弄清楚 URL 的哪些部分位于哪些字段中,而且我在网上找不到任何相关示例。我特别想知道应该如何将 URL 分解为Path、PathBase和QueryString变量。

例如,假设我想构建 URL "http://example.com/route/endpoint?foo=bar"。我很确定我的QueryString只是"?foo=bar",但我不知道如何将 URL 的其余部分分解为其他字段。另请告诉我,除了我提到的三个相关字段之外,是否还有其他字段与 相关GetDisplayUri。

如果有任何不清楚的地方请告诉我。

Tom*_*Tom 5

好吧,经过大约一个小时的反复试验,我已经弄清楚哪些字段映射到网址的哪个部分。一般形式为 ,url = [Scheme]://[Host][PathBase][Path][QueryString]并且它们各自都有关于如何连接它们的特定规则(例如,Path 和 PathBase 必须以 开头/)。

因此,在问题 ( ) 的示例中"http://example.com/route/endpoint?foo=bar",您的 HttpRequest 对象将需要以下字段。

var request = class_implementing_HttpRequest() {
    Scheme = "http",
    Host = new HostString("example.com"),
    PathBase = new PathString("/route"),
    Path = new PathString("/endpoint"),
    QueryString = new QueryString("?foo=bar")
}
Run Code Online (Sandbox Code Playgroud)

由于 的实现是隐藏的,所以弄清楚这一点有点令人讨厌GetDisplayUri。希望如果其他人遇到这种情况,我可以为您节省一个小时的猜测和检查时间。

编辑:正如 David 在其答案的评论中指出的那样,.NET Core 是开源的,我可以在此处找到答案。