VS2022 C# 中的 Http Post Json

问题描述 投票:0回答:1

我有json文件。当我通过邮递员(应用程序)发送它时,它可以工作,但在 C# 代码中我得到“错误请求”

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

我找不到问题

c# json httpclient .net-4.6.2
1个回答
0
投票

也许您需要将 JObject 更改为字典。

请参阅此参考:https://www.geekinsta.com/send-x-www-form-urlencoded-post-request-using-httpclient-in-c/

© www.soinside.com 2019 - 2024. All rights reserved.