Http Post Json in VS2022 C#

124 views Asked by At

I have json file. When I send it by Postman (Application) it works but in C# code I get "Bad Request"

The Json File:

{
    "name": "Token",
    "request": {
        "method": "POST",
        "header": [
            {
                "key": "Content-Type",
                "value": "application/x-www-form-urlencoded"
            },
            {
                "key": "Authorization",
                "value": "Basic cm9jbGllbnQ6c2VjcmV0"
            }
        ],
        "body": {
            "mode": "raw",
            "raw": "grant_type=password&username=TestUser&password=@Sep123456&scope=SepCentralPcPos openid"
        },
        "url": {
            "raw": "https://idn.seppay.ir/connect/token",
            "protocol": "https",
            "host": [
                "idn",
                "seppay",
                "ir"
            ],
            "path": [
                "connect",
                "token"
            ]
        }
    },
    "response": []
}

I tried this code

public async Task<String> GET_TOKEN()
{
    try
    {
        JObject body = new JObject();
        body.Add("mode", "raw");
        body.Add("raw", "grant_type=password&username=TestUser&password=@Sep123456&scope=SepCentralPcPos openid");

        using (var httpClient = new HttpClient())
        {
            using (var request = new HttpRequestMessage(new HttpMethod("POST"), TokenAddress))
            {
                //request.Headers.TryAddWithoutValidation("Authorization", "Basic cm9jbGllbnQ6c2VjcmV0");
                request.Content = new StringContent(body.ToString(), Encoding.UTF8, "application/json");
                request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
                
                var response = await httpClient.SendAsync(request);
                string responseBody = await response.Content.ReadAsStringAsync();

                JObject jsnResualt = JsonConvert.DeserializeObject<JObject>(responseBody);

                string token = "";
                long expiresIn = 0;
                return "";
            }
        }
    }
    catch (Exception ex)
    {
        return "";
    }
}

I could not find the problem

1

There are 1 answers

0
Esmail On BEST ANSWER

This not post by Json If post by HttpClient it will work

using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("https://idn.seppay.ir/connect/token");
            client.DefaultRequestHeaders.Add("Authorization", "Basic cm9jbGllbnQ6c2VjcmV0");
            var content = new StringContent("grant_type=password&username=TestUser&password=@Sep123456&scope=SepCentralPcPos openid", null, "application/x-www-form-urlencoded");
            
            var result = client.PostAsync("", content).Result;
            string resultContent = result.Content.ReadAsStringAsync().Result;
        }