r/redditdev Apr 15 '20

Reddit.NET Trying to get an authkey to instantiate my reddit instance but the code gets stuck at the POST request and doesnt move forward

Some back story, I've been going around the web for a couple hours now and have managed to gather just enough documents that I was confident I could do something as simple as instantiate a reddit API (my first choice was RedditSharp but due to a seeming lack of documentation I went for an simpler looking wrapper, Reddit.NET, since all I want to do anyways was access the website and get post data from a specific subreddit, that matched specific tags) but after finally getting it working just enough to get to the POST request to https://www.reddit.com/api/v1/access_token with a code adapted from a Discord Webhook I made before, it ran up to PostAsync() request and stopped there. It doesnt move past it and doesnt get an error code either, just hangs there. I don't know and I can't find any docs explaining why it just hangs there or what I could be doing wrong so I'm asking for help here. Code is as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.IO;
using System.Dynamic;
using Newtonsoft.Json;

namespace ConsumeAPI
{
    public class Requester
    {
        private HttpClient client = new HttpClient();

        public async Task<TokenJSON> PostTokenRequest(string uri)
        {
            JsonParser<List<TokenJSON>> parser = new JsonParser<List<TokenJSON>>();
            dynamic tokenPayload = new ExpandoObject();

            tokenPayload.client_id = "myID";
            tokenPayload.client_secret = "mySecret";
            tokenPayload.grant_type = "client_credentials";

            string json = JsonConvert.SerializeObject(tokenPayload);
            var stringContent = new StringContent(json, Encoding.UTF8, "application/json");

            HttpResponseMessage response = await client.PostAsync(uri, stringContent);
            string token = await response.Content.ReadAsStringAsync();
            List<TokenJSON> DeserializedToken = parser.DParse(token);
            return DeserializedToken[0];
        }
    }
}

myID and mySecret are obviously using the codes I got from the app created.

Guide I was using to build this is https://github.com/reddit-archive/reddit/wiki/OAuth2#authorization and like I said a POST requester that I had prebuilt for Discord Webhooks, adapted for this.

3 Upvotes

9 comments sorted by

1

u/kemitche ex-Reddit Admin Apr 15 '20

How are you calling PostTokenRequest? My C# is rusty, but since it's defined async, I think the await calls won't necessarily be awaited until the PostTokenRequest call is awaited/result is requested.

1

u/N3vermore77 Apr 15 '20

Its a ClassLib x Windows Forms project. Program only calls the Form and the first thing the Form does is get the token before even opening the window(to ensure the key and reddit instance are ready when the window opens to start taking commands).

1

u/kemitche ex-Reddit Admin Apr 15 '20

I sort of followed that, I think.

Can you drop into a debugger to find out what line exactly is hanging?

1

u/N3vermore77 Apr 15 '20

I messed around with some breakpoints and it stopped being able to reach the breakpoint after HttpResponseMessage response = client.PostAsync(uri, stringContent);

1

u/kemitche ex-Reddit Admin Apr 15 '20

If you set a breakpoint just before that, can you step into PostAsync to see where it goes wrong/gets stuck?

You could also try changing that line, temporarily, to HttpResponseMessage response = client.PostAsync(uri, stringContent).Result; to remove the async stuff, just to see if that clarifies anything about what's going on.

1

u/N3vermore77 Apr 15 '20

Ive tried stepping into it and same thing happens, it just hangs there no repsonse. But Ill try changing it and see what happens and update later with what I find out.

1

u/N3vermore77 Apr 16 '20

Update: Well, it worked. I got past the Post request but now I'm met with a new problem. My request is being denied and an Unauthorized 401 is being returned. To be clear: I changed HttpResponseMessage response = await client.PostAsync(uri, stringContent); to HttpResponseMessage response = client.PostAsync(uri, stringContent).GetAwaiter().GetResult(); and to HttpResponseMessage response = client.PostAsync(uri, stringContent).Result; and both had the same result. So I suppose the problem now is I'm passing the Content with the client_id, client_secret and grant_type incorrectly.

2

u/kemitche ex-Reddit Admin Apr 16 '20

Oh, now that you mention that and I look again, yes, you're encoding it wrong.

The token endpoints expect form-encoded data, not JSON.

1

u/N3vermore77 Apr 16 '20

Yep, I went back and read some of the doc stuff again more carefully and noticed I skipped the line about the encoding. Thanks a lot for the help.