【问题标题】:Getting an error message saying missing parameter in StringContent, but it is present?收到一条错误消息,说明 StringContent 中缺少参数,但它存在?
【发布时间】:2020-11-14 04:33:30
【问题描述】:

有这样一段代码:

 using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
        request.Headers.TryAddWithoutValidation("User-Agent", userAgent);
        request.Content = new StringContent("{" +
                    $"\"grant_type\":\"authorization_code\"," +
                    $"\"client_id\":\"*****\"," +
                    $"\"client_secret\":\"****\"," +
                    $"\"code\":\"{autorizationCode}\"," +
                    $"\"redirect_uri\":\"urn:ietf:wg:oauth:2.0:oob\"" +
                    "}", Encoding.UTF8);

        var response = await client.SendAsync(request);
        Token = response.Content.ReadAsStringAsync().Result.ToString();
    }

当我发送请求时,它给了我一个错误 - "{"error":"invalid_request","error_description":"Missing required parameter: grant_type."}",但 grant_type 存在。

网站上的请求如下所示:

curl -X POST "https://site/oauth/token" \
-H "User-Agent: APPLICATION_NAME" \
-F grant_type="authorization_code" \
-F client_id="CLIENT_ID" \
-F client_secret="CLIENT_SECRET" \
-F code="AUTORIZATION_CODE" \
-F redirect_uri="REDIRECT_URI"

他为什么给出这个错误?我该如何解决?

【问题讨论】:

  • 这能回答你的问题吗? Load JSON string to HttpRequestMessage
  • 您需要将内容类型设置为"application/json"。我也不会像这样自己构建 JSON,使用 JSON 序列化器,如 Json.Net
  • omg,谢谢,当我在 mediaType StringContent 中添加“application/json”时它起作用了。

标签: c# json http curl httpclient


【解决方案1】:

CURL-参数 -F 代表表单内容,而不是 JSON 内容。

如果要发送FormContent,不能使用StringContent,需要使用FormUrlEncodedContent,像这样:

using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
        request.Headers.TryAddWithoutValidation("User-Agent", userAgent);
        request.Content = new FormUrlEncodedContent( new List<KeyValuePair<string, string>>() {
              new KeyValuePair<string,string>("grant_type", "authorization_code"),
              new KeyValuePair<string,string>("client_id", "*****"),
              new KeyValuePair<string,string>("client_secret", "*****"),
              new KeyValuePair<string,string>("code", $"{autorizationCode}"),
              new KeyValuePair<string,string>("redirect_uri", "urn:ietf:wg:oauth:2.0:oob")
       } );

        var response = await client.SendAsync(request);
        Token = response.Content.ReadAsStringAsync().Result.ToString();
    }

/Edit:关于您的评论,您的端点也支持 JSON,但您错过了内容类型。我会把这个留在这里,以防有人遇到你提到的确切 CURL 请求的问题。

【讨论】:

  • 非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-20
  • 2018-06-03
  • 2021-04-19
  • 1970-01-01
  • 1970-01-01
  • 2020-06-22
  • 1970-01-01
相关资源
最近更新 更多