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
)
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?