0

I am trying to re-create a postman request in C#. Below a screenshot of the postman request that works:

(The header is application/json) enter image description here

and the C# that does not:

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

The response from the C# code is:

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

I am very confused as to what I am missing. I clearly have the grant_type provided. However not matter what I set grant_type to I get the same error message listed above. I suspected it might be something to do with the content-type. On the valid request in Postman I clicked code -> then cURL and it gave me this:

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

I tried adding the missing headers to my request by doing this (just above the try block):

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

But then I was met with error 500 responses (if I have application/json and multipart/form-data) and Unsupported Media Type if I just have application/json

I am completely stumped here. Any ideas what I am doing wrong?

duck
  • 747
  • 14
  • 31
  • Does curl return same error or it's working as expected? – Aleks Andreev Apr 08 '19 at 17:06
  • so the C# code is supposed to respond to the request? Yet your request is a POST where as your C# is a GET? – mvermef Apr 08 '19 at 17:08
  • @AleksAndreev cURL is working as expected – duck Apr 08 '19 at 17:27
  • @mvermef it was a POST request at first but I changed some stuff around (like removing the arguments (client_id, etc) and hardcoding them. Whether it's GET or POST I get the same response: the error in the OP – duck Apr 08 '19 at 17:29
  • @duckwizzle Try to create request with "content type = application/x-www-form-urlencoded", [this is example](https://stackoverflow.com/questions/43158250/how-to-post-using-httpclient-content-type-application-x-www-form-urlencoded/43158324#43158324) – Vladimir Apr 08 '19 at 19:25
  • @Vladimir Same error message. It's like it doesn't see the grant_type at all – duck Apr 08 '19 at 19:33
  • @duckwizzle If you have a working request in Postman, generate C# code snippet - C#(RestSharp), same way as you did with cURL. Compare generated request details with your code. Are you trying to implement Client Credentials flow or Authorization Code flow? – Vladimir Apr 08 '19 at 20:46
  • @Vladimir Yeah I saw the RestSharp example it provided but did not test it because I am not using RestSharp. Here is the generated C# snippet: https://pastebin.com/vnm7RZ0Z . I am trying write an endpoint that will generate the access_token needed to preform other calls to a 3rd party API - so I guess authorization code flow. – duck Apr 08 '19 at 21:05

0 Answers0