Take the 2-minute tour ×
Stack Apps is a question and answer site for apps, scripts, and development with the Stack Exchange API. It's 100% free, no registration required.

I'm making an application in C# and I need to both search and post answers, so I need an access token.

I found some information, libraries, and code pieces:

I registered my application and I have a client ID. But, when I surf the following, I get a 500 error:

https://stackexchange.com/oauth/dialog?client_id=3408&scope=no_expiry&redirect_uri=https://stackexchange.com/oauth/login_success

The page says:

This app needs these permissions
•Perpetual access to this data
•To know what your accounts are on the Stack Exchange network

My c# code is:

string url2 = "https://stackexchange.com/oauth/dialog?client_id=3408&scope=no_expiry&redirect_uri=https://stackexchange.com/oauth/login_success"; 

HttpWebRequest requestLog = (HttpWebRequest)HttpWebRequest.Create(url2);

using (HttpWebResponse responseLog = (HttpWebResponse)requestLog.GetResponse())
{
    NameValueCollection urlParameters = HttpUtility.ParseQueryString(responseLog.ResponseUri.Query);

    // extract the access token from the url.

    string accessToken = urlParameters["access_token"];
}

OR :

string url="https://stackexchange.com/oauth/dialog?client_id=3408&scope=no_expiry&redirect_uri=https://stackexchange.com/oauth/login_success";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
    StreamReader reader = new StreamReader(response.GetResponseStream());

    string vals = reader.ReadToEnd();

    foreach (string token in vals.Split('&'))
    {                       
        tokens.Add(token.Substring(0, token.IndexOf("=")),
            token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
    }
}

string access_token = tokens["access_token"];


I searched in the net and couldn't find a good article about that. Please let me know what I need to make this work.

share|improve this question

1 Answer 1

In a nutshell and don't know ask me how to write this in C#:

  1. That first "500 error" page is normal. You must display that to the user and the user must approve.
  2. When the user approves, the page will redirect to a page (nominally stackexchange.com/oauth/login_success) with the access_token in the URL parameters. For example:

    https://stackexchange.com/oauth/login_success#access_token=aJHxxxxx6ALzmg7Kc1gc9Q%29%29&expires=86399
    
  3. Extract that access_token (aJHxxxxx6ALzmg7Kc1gc9Q)) in our example) and then you can use it in subsequent HTTP POSTs until it expires or until the user de-authorizes your app.

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .