Hi guys!
I’ve been trying to wrap the Twitch web API with some simple C# code for myself. I’m using Windows Universal Dotnet. One of the first functions in the API guide is refreshing your access token.
My problem is that the response doesn’t match up with what I expect when I code it in C#. But recreating the same request in Postman works as expected. Please let me know if this isn’t the right place to post such a coding-centric question.
I spent some time including a bunch of screenshots but I’m not allowed to post more than one for now. I made an imgur album instead. I hope that’s okay!
So basically I created 2 requests that have the same request body. The request from Postman received a message of “invalid client secret,” which is totally expected. The request from C# received a message of “missing client id,” which is totally unexpected. It’s clearly in the request body though and the Content-Type is set to application/json just like Postman. Anyone have any ideas? If you’d like, I’m happy to post the code as well.
Can you share the code making the request or minimal code enough to repro? The one difference I see that could theoretically make a difference (but shouldn’t) is the charset being specified at the end of the content-type header. I know it has caused issues for me with elasticsearch, for example. You can remove it with hc.Headers.ContentType.CharSet = "";, where hc is your HttpContent.
Ha! This actually seems to have fixed it. Here’s a small console application showcasing it:
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace Temp
{
class Program
{
public static async Task<string> RefreshToken()
{
using (var client = new HttpClient())
{
var post = new HttpRequestMessage(HttpMethod.Post, "https://id.twitch.tv/oauth2/token");
var body = new
{
client_id = "kojortd5rhu0bzoamqm6zlsh0mewsu",
grant_type = "refresh_token",
client_secret = "none",
refresh_token = "none"
};
var json = JsonConvert.SerializeObject(body);
post.Content = new StringContent(json, Encoding.UTF8, "application/json");
post.Content.Headers.ContentType.CharSet = ""; // THE FIX
var responseMessage = await client.SendAsync(post);
var response = await responseMessage.Content.ReadAsStringAsync();
return response;
}
}
static void Main(string[] args)
{
Console.WriteLine(RefreshToken().Result);
Console.ReadKey();
}
}
}
That one commented line is all it needed. Unfortunately, I don’t think there’s a way to specify that the ContentType is application/json without specifying the charset. So that extra line is needed.
Anyway, I wouldn’t have thought that that mattered. Thank you very much, 3v!