收到一条错误消息,指出 StringContent 中缺少参数,但它存在?

Getting an error message saying missing parameter in StringContent, but it is present?

有这样一个代码:

 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"

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

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

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