2

我编写了以下代码。当用户单击超链接时,他将被重定向到登录页面,返回 URL 为https://localhost:44300/Office365/Office365Response。我编写了以下代码来获取访问令牌。但我总是收到如下所示的错误。我哪里错了?

抱歉,我们无法让您登录。我们收到了错误的请求。其他技术信息:相关 ID:2e875fd4-f5a6-4003-9887-357c4a890e90 时间戳:2016-01-19 08:28:20Z AADSTS90056:此端点仅接受 POST 请求。

其他技术信息:相关 ID:2e875fd4-f5a6-4003-9887-357c4a890e90 时间戳:2016-01-19 08:28:20Z AADSTS90056:此端点仅接受 POST 请求。

    public ActionResult Office365Response(string code, string session_state)
    {
        string url = "http://login.microsoftonline.com/common/oauth2/token";
        code = "{Code}";
        string postData = "client_id" + "=" + "{ClientId}";
        postData += "&" + "redirect_uri" + "=" + "https://localhost:44300/Office365/Office365Response";
        postData += "&" + "client_secret" + "=" + "{ClientSecret}";
        postData += "&" + "code" + "=" + code;
        postData += "&" + "grant_type=authorization_code";
        postData += "&" + "resource" + "=" + "https://api.office.com/discovery/";

        // Create a request using a URL that can receive a post. 
        WebRequest request = WebRequest.Create(url);
        request.UseDefaultCredentials = true;
        request.PreAuthenticate = true;
        request.Credentials = CredentialCache.DefaultCredentials;
        // Set the Method property of the request to POST.
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        // Create POST data and convert it to a byte array.
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        // Set the ContentType property of the WebRequest.

        // Set the ContentLength property of the WebRequest.
        request.ContentLength = byteArray.Length;
        // Get the request stream.
        Stream dataStream = request.GetRequestStream();
        // Write the data to the request stream.
        dataStream.Write(byteArray, 0, byteArray.Length);
        // Close the Stream object.
        dataStream.Close();
        // Get the response.
        WebResponse response = request.GetResponse();
        // Display the status.
        Console.WriteLine(((HttpWebResponse)response).StatusDescription);
        // Get the stream containing content returned by the server.
        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.
        reader.Close();
        dataStream.Close();
        response.Close();
}
4

0 回答 0