Search code examples
c#asp.netauthenticationwindows-live

Getting error while fetching information from windows live server


I am trying to authenticate user through windows live account with following code.

byte[] byteArray = Encoding.UTF8.GetBytes(postData);
 WebRequest request = WebRequest.Create("https://oauth.live.com/token");
 request.ContentType = "application/x-www-form-urlencoded";
 request.ContentLength = byteArray.Length;
 request.Method = "POST"; 
 Stream resp = request.GetRequestStream();
 Stream dataStream = request.GetRequestStream();
 dataStream.Write(byteArray, 0, byteArray.Length);
 var response = request.GetResponse();

But I am getting following error at last line.

The remote server returned an error: (400) Bad Request.

what should I do for this?


Solution

  • Your issue is probably because we do not send bytes on "application/x-www-form-urlencoded" post but a string. Also the GetRespose is not looks like the correct one. Your code must be something like:

    // I do not know how you create the byteArray
    byte[] byteArray = Encoding.UTF8.GetBytes(postData);
    // but you need to send a string
    string strRequest = Encoding.ASCII.GetString(byteArray);
    
    WebRequest request = WebRequest.Create("https://oauth.live.com/token");
    request.ContentType = "application/x-www-form-urlencoded";
    
    // not the byte length, but the string
    //request.ContentLength = byteArray.Length;
    request.ContentLength = strRequest.Length;
    
    request.Method = "POST"; 
    
    using (StreamWriter streamOut = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII))
    {
        streamOut.Write(strRequest);
        streamOut.Close();
    }
    
    string strResponse;
    // get the response
    using (StreamReader stIn = new StreamReader(request.GetResponse().GetResponseStream()))
    {
        strResponse = stIn.ReadToEnd();
        stIn.Close();
    }
    
    // and here is the results
    FullReturnLine = HttpContext.Current.Server.UrlDecode(strResponse);