UTF-8 网址编码 [英] UTF-8 URL Encode

查看:61
本文介绍了UTF-8 网址编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 HttpUtility.UrlEncode() 编码我的查询参数时遇到问题,它没有转换为 UTF-8.

I am having issues in encoding my query params using HttpUtility.UrlEncode() it is not getting converted to UTF-8.

 query["agent"] = HttpUtility.UrlEncode("{\"mbox\":\"mailto: UserName@company.com\"}");

我尝试使用重载方法并通过 utf 编码,但仍然无法正常工作.

I tried using the overload method and passed utf encoding but still it is not working.

预期结果:

?agent=%7B%22mbox%22%3A%22mailto%3AUserName%40company.com%22%7D

实际结果:

?agent=%257b%2522mbox%2522%253a%2522mailto%253aUserName%2540company.com%2522%257d

     public StatementService(HttpClient client, IConfiguration conf)
    {
        configuration = conf;
        var BaseAddress = "https://someurl.com/statements?";             
        client.BaseAddress = new Uri(BaseAddress);
        client.DefaultRequestHeaders.Add("Custom-Header", 
                                          "customheadervalue");
        Client = client;
    }

   public async Task<Object> GetStatements(){
     var query = HttpUtility.ParseQueryString(Client.BaseAddress.Query);
     query["agent"] = HttpUtility.UrlEncode( "{\"mbox\":\"mailto:UserName@company.com\"}");

        var longuri = new Uri(Client.BaseAddress + query.ToString());
        
        var response = await Client.GetAsync(longuri);
        response.EnsureSuccessStatusCode();

        using var responseStream = await response.Content.ReadAsStreamAsync();

        dynamic statement = JsonSerializer.DeserializeAsync<object>(responseStream);
 //Convert stream reader to string 
        StreamReader JsonStream = new StreamReader(statement);
        string JsonString = JsonStream.ReadToEnd();
        //convert Json String to Object.
        JObject JsonLinq = JObject.Parse(JsonString);
        // Linq to Json
        dynamic res = JsonLinq["statements"][0].Select(res => res).FirstOrDefault();
        return await res;

}

推荐答案

HttpUtility.ParseQueryString 方法在内部返回一个 HttpValueCollection.HttpValueCollection.ToString() 已经执行了 url 编码,所以你不需要自己做.如果你自己做,它会执行两次,你会得到你看到的错误结果.

The method HttpUtility.ParseQueryString internally returns a HttpValueCollection. HttpValueCollection.ToString() already performs url encoding, so you don't need to do that yourself. If you do it yourself, it is performed twice and you get the wrong result that you see.

我没有看到与 UTF-8 的关系.您使用的值 ({"mbox":"mailto: UserName@company.com"}) 不包含任何在 UTF-8 中看起来不同的字符.

I don't see the relation to UTF-8. The value you use ({"mbox":"mailto: UserName@company.com"}) doesn't contain any characters that would look different in UTF-8.

参考文献:

这篇关于UTF-8 网址编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆