\ 正在转换为 / C# Uri 类

问题描述 投票:0回答:1

我正在尝试使用 HttpClient 发出获取请求。下面是我的代码。

var url = new Uri("https://example.com/api/v1/tenants/T01UZ1/module/users/abc\userid/tokens");


HttpResponseMessage response = await _httpClient.GetAsync(url);

一旦我创建 Uri 对象,“abc\userid”就会转换为“abc/userid”。反斜杠正在转换为正斜杠。

我也尝试使用下面的构造函数重载。这里第二个参数是dontEscape。我知道这种超载已经过时,但我想尝试一下。当我调试相同的内容时,我发现 Uri 的值

OriginalString
属性为 https://example.com/api/v1/tenants/T01UZ1/module/users/abc\userid/tokens

var url = new Uri("https://example.com/api/v1/tenants/T01UZ1/module/users/abc\userid/tokens", true);

但是,当我检查 resposne 变量的 RequestMessage 属性时,它仍然不正确(带有 /)。

我还尝试使用

Uri.EscapeDataString
Uri.EscapeString

进行编码 \

所以代码是

var url = new Uri("https://example.com/api/v1/tenants/T01UZ1/module/users/abc%5Cuserid/tokens", true);

但是上面也在做同样的事情。它正在创建如下所示的 URL。

https://example.com/api/v1/tenants/T01UZ1/module/users/abc/userid/tokens

这背后的原因可能是什么? abc\user 是带有域名的用户 ID。这里abc可以认为是域名。

c# .net-core uri dotnet-httpclient
1个回答
0
投票

我尝试了以下方法:

using System;
using System.Web;
using System.Net.Http;
using System.Threading.Tasks;

public class Program
{
    static readonly HttpClient client = new HttpClient();
        
    public static async Task Main()
    {
            
        var url = new Uri( @"https://example.com/api/v1/tenants/T01UZ1/module/users/" + HttpUtility.UrlEncode( @"abc\userid/tokens" ) );

        Console.WriteLine( url.ToString() );
            
        try
        {
            using HttpResponseMessage response = await client.GetAsync( url );
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseBody);
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine("\nException Caught!");
            Console.WriteLine("Message :{0} ", e.Message);
        }
        
    }
    
}

结果是:

https://example.com/api/v1/tenants/T01UZ1/module/users/abc%5cuserid%2ftokens

Exception Caught!
Message :Response status code does not indicate success: 500 (Internal Server Error). 
© www.soinside.com 2019 - 2024. All rights reserved.