无法在C#Web API中重新创建此邮递员请求-unsupported_grant_type

时间:2019-04-08 17:02:28

标签: c# asp.net-web-api asp.net-core

我正在尝试使用C#重新创建邮递员请求。在有效的邮递员请求的屏幕截图下方:

(标题为application/jsonenter image description here

和没有的C#:

[HttpGet]
[Route("GenerateAccessToken")]
[ProducesResponseType(typeof(bool), (int)HttpStatusCode.OK)]
[ProducesResponseType(typeof(bool), (int)HttpStatusCode.BadRequest)]
[ProducesResponseType(typeof(bool), (int)HttpStatusCode.InternalServerError)]
public async Task<ActionResult<AccessTokenResponse>> GenerateAccessToken()
{
    var client = new HttpClient();

    MultipartFormDataContent clientData = new MultipartFormDataContent
    {
        { new StringContent("[Removed]"), "client_id" },
        { new StringContent("[Removed]"), "client_secret" },
        { new StringContent("client_credentials"), "grant_type" },
    };

    try
    {
        var responseObject = new AccessTokenResponse();
        var response = await client.PostAsync(AccessTokenEndpoint, clientData);
        var responseString = await response.Content.ReadAsStringAsync();

        if (response.IsSuccessStatusCode)
        {
            responseString = await response.Content.ReadAsStringAsync();
            responseObject = JsonConvert.DeserializeObject<AccessTokenResponse>(responseString);

            return Ok(responseObject);
        }

        return StatusCode(400, responseObject);
    }
    catch (Exception ex)
    {
        Logger.Log(ex);
        return StatusCode(500, false);
    }
}

C#代码的响应是:

{"error":"unsupported_grant_type","error_description":"Use \"authorization_code\" or \"refresh_token\" or \"client_credentials\" or \"urn:ietf:params:oauth:grant-type:jwt-bearer\" as the grant_type.","error_uri":"https://developer.salesforce.com/docs"}

我对我所缺少的感到非常困惑。我显然提供了grant_type。但是,不管我将grant_type设置为什么,都会得到上面列出的相同错误消息。我怀疑这可能与content-type有关。在邮递员中的有效请求上,我单击代码->然后单击cURL,它给了我这个信息:

curl -X POST \
  https://[removed].auth.marketingcloudapis.com/v2/token \
  -H 'Content-Type: application/json' \
  -H 'Postman-Token: f469a34a-194e-44b4-82aa-c5d46a1528f7' \
  -H 'cache-control: no-cache' \
  -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
  -F client_id=[removed] \
  -F client_secret=[removed] \
  -F grant_type=client_credentials

我尝试通过执行以下操作(在try块上方)将缺少的标头添加到我的请求中:

clientData.Headers.TryAddWithoutValidation("Content-Type", "application/json");
clientData.Headers.TryAddWithoutValidation("Content-type", "multipart/form-data");
//clientData.Headers.TryAddWithoutValidation("Content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");

但是后来我遇到了错误500响应(如果我有application/jsonmultipart/form-data)和Unsupported Media Type,如果我只有application/json

我完全被困在这里。有什么想法我做错了吗?

0 个答案:

没有答案