user_0_found
user_0_found

Reputation: 121

.net core HTTPS requests returns 502 bad gateway while Postman returns 200 OK

What's wrong with this code snippet in 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());
            }
        }
    }
}

When running this with a breakpoint at the line response.EnsureSuccessStatusCode(), I always get 502 response. However, if running this in Postman or in curl, I got back a valid result.

Example in curl:

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

Many thanks for helping a newbie out!

Upvotes: 1

Views: 2163

Answers (1)

haldo
haldo

Reputation: 16711

The request uses application/x-www-form-urlencoded so instead of StringContent use FormUrlEncodedContent:

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

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

Upvotes: 1

Related Questions