سؤال

I have to use HttpWebRequest in C#, to retrieve an access token.

My base url redirects me to another url that contains the access token.

Is there a way to use this to get the access token?

This is my code after applying suggestions from the answer:

 // Create a request for the URL. 
            string url = "https://stackexchange.com/oauth/dialog?client_id=2532&scope=no_expiry&redirect_uri=https://stackexchange.com/oauth/login_success"; 
            WebRequest request = WebRequest.Create(
              url);
            request.Method = "GET";
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.
            WebResponse response = request.GetResponse();
            // Display the status.
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Console.WriteLine(responseFromServer);
            // Clean up the streams and the response.
            reader.Close();
            response.Close();

Debug breaks at line: WebResponse response = request.GetResponse(); VS tells me that the server has the a generic error: 500. If I try with https://www.google.com, no errors.

هل كانت مفيدة؟

المحلول

You can get the resulting url from the ResponseUri property.

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    NaveValueCollection urlParameters = HttpUtility.ParseQueryString(response.ResponseUri.Query);

    // extract the access token from the url.

    string accessToken = urlParameters["access_token"];
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top