首页 > 解决方案 > .net core HTTPS 请求返回 502 bad gateway 而 Postman 返回 200 OK

问题描述

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

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());
            }
        }
    }
}

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

卷曲中的示例:

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

非常感谢您帮助新手!

标签: c#posthttps.net-coredotnet-httpclient

解决方案


请求使用application/x-www-form-urlencodedso 而不是StringContentuse FormUrlEncodedContent

var content = new FormUrlEncodedContent(req);
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

var response = await httpClient.PostAsync(uriBuilder.Uri, content);

推荐阅读