Search code examples
c#jsonhttpwebrequest.net-coretwitch

.NETCore HttpWebRequest - Old Way isn't Working


Before I upgraded to the newest .NetCore I was able to run the HttpWebRequest, add the headers and content Type and pull the stream of the JSON file from Twitch. Since the upgrade this is not working. I receive a Web Exception each time I go to get the response Stream. Nothing has changed with twitch because it still works with the old Bot. The old code is below:

private const string Url = "https://api.twitch.tv/kraken/streams/channelname";
HttpWebRequest request;
        try
        {
            request = (HttpWebRequest)WebRequest.Create(Url);
        }

        request.Method = "Get";
        request.Timeout = 12000;
        request.ContentType = "application/vnd.twitchtv.v5+json";
        request.Headers.Add("Client-ID", "ID");
        try
        {
            using (var s = request.GetResponse().GetResponseStream())
            {
                if (s != null)
                    using (var sr = new StreamReader(s))
                    {

                    }
            }
        }

I have done some research and found that I may need to start using either an HttpClient or HttpRequestMessage. I have tried going about this but when adding headers content type the program halts and exits. after the first line here: (when using HttpsRequestMessage)

request.Content.Headers.ContentType.MediaType = "application/vnd.twitchtv.v5+json";
request.Content.Headers.Add("Client-ID", "rbp1au0xk85ej6wac9b8s1a1amlsi5");

Solution

  • You are trying to add a ContentType header, but what you really want is to add an Accept header (your request is a GET and ContentType is used only on requests which contain a body, e.g. POST or PUT).

    In .NET Core you need to use HttpClient, but remember that to correctly use it you need to leverage the use of async and await.

    Here it is an example:

    using System.Net.Http;
    using System.Net.Http.Headers;
    
    private const string Url = "https://api.twitch.tv/kraken/streams/channelname";
    
    public static async Task<string> GetResponseFromTwitch()
    {
        using(var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.twitchtv.v5+json"));
            client.DefaultRequestHeaders.Add("Client-ID", "MyId");
    
            using(var response = await client.GetAsync(Url))
            {
                response.EnsureSuccessStatusCode();
    
                return await response.Content.ReadAsStringAsync(); // here we return the json response, you may parse it
            }
        }    
    }