【问题标题】:.net core HTTPS requests returns 502 bad gateway while Postman returns 200 OK.net core HTTPS 请求返回 502 bad gateway 而 Postman 返回 200 OK
【发布时间】:2019-12-08 14:09:43
【问题描述】:

C#.NET core 3 中这段代码 sn-p 有什么问题:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var uriBuilder = new UriBuilder
            {
                Scheme = Uri.UriSchemeHttps,
                Host = "api.omniexplorer.info",
                Path = "v1/transaction/address",
            };

            var req = new Dictionary<string, string>
            {
                { "addr", "1FoWyxwPXuj4C6abqwhjDWdz6D4PZgYRjA" }
            };

            using(var httpClient = new HttpClient())
            {
                var response = await httpClient.PostAsync(uriBuilder.Uri, new StringContent(JsonConvert.SerializeObject(req)));
                response.EnsureSuccessStatusCode();
                Console.WriteLine(response.Content.ToString());
            }
        }
    }
}

response.EnsureSuccessStatusCode() 行使用断点运行此程序时,我总是得到 502 响应。但是,如果在 Postman 或 curl 中运行它,我会得到一个有效的结果。

curl 中的示例:

curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "addr=1EXoDusjGwvnjZUyKkxZ4UHEf77z6A5S4P" "https://api.omniexplorer.info/v1/transaction/address"

非常感谢您帮助新手!

【问题讨论】:

    标签: c# post https .net-core dotnet-httpclient


    【解决方案1】:

    请求使用application/x-www-form-urlencoded 所以而不是StringContent 使用FormUrlEncodedContent

    var content = new FormUrlEncodedContent(req);
    content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
    
    var response = await httpClient.PostAsync(uriBuilder.Uri, content);
    

    【讨论】:

    • 哇,谢谢。这样可行。但是,我必须删除content.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); 行,因为它会产生异常:Cannot add value because header 'Content-Type' does not support multiple values. 我们应该先调用content.Headers.Clear() 之类的东西吗?
    • @user_0_found 我已经更新了答案 - FormUrlEncodedContent 有一个 ContentType 属性,应该使用它来代替 Headers.Add。希望现在对你有用
    猜你喜欢
    • 2019-05-29
    • 2020-06-14
    • 2021-02-24
    • 1970-01-01
    • 1970-01-01
    • 2019-03-03
    • 1970-01-01
    • 2019-08-24
    • 2018-10-08
    相关资源
    最近更新 更多