VS2022 C#中的Http Post JSON

ijxebb2r  于 12个月前  发布在  C#
关注(0)|答案(1)|浏览(195)

我有json文件。当我通过Postman(应用程序)发送它时,它可以工作,但在C#代码中,我得到了“Bad Request”
Json文件:

{
    "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": []
}

字符串
我试过这个密码

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 "";
    }
}


我找不到问题

3mpgtkmj

3mpgtkmj1#

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

字符串

相关问题