在 Spotify API 令牌检索上出现 500 内部服务器错误

Getting a 500 internal server error on Spotify API Token Retrieval

我正在努力从 Spotify API 获取访问令牌,但我无法取回它。在能够获取授权代码并完成该过程后尝试时,我遇到了 500 内部服务器错误。这是我的代码:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SpotifyAPI
{
    public partial class Callback : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string code = Request.QueryString["code"];
            string state = Request.QueryString["state"];

            // Generate URL with authorization code
            string url = "https://accounts.spotify.com/api/token?grant_type=authorization_code&code=" + code + "&redirect_uri=http://localhost:64270/Callback.aspx";

            // get Client ID and Secret
            string clientId = ((Site1)this.Master).getClientId();
            string clientSecret = ((Site1)this.Master).getClientSecret();

            // generate encoded header string for token request
            string preAuthorizationCode = clientId + ":" + clientSecret;
            string postAuthorizationCode = Base64Encode(preAuthorizationCode);
            Debug.WriteLine("Post Authorization Code is: " + postAuthorizationCode);

            var webrequest = (HttpWebRequest)WebRequest.CreateHttp(url);
            webrequest.Method = "POST";

            WebHeaderCollection myWebHeaderCollection = webrequest.Headers;
            myWebHeaderCollection.Add("Authorization: Basic " + postAuthorizationCode);

            HttpWebResponse myHttpWebResponse = (HttpWebResponse)webrequest.GetResponse();

            Stream responseStream = myHttpWebResponse.GetResponseStream();
            var reader = new StreamReader(responseStream);
            string result = reader.ReadToEnd();
        }

        public static string Base64Encode(string plainText)
        {
            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
            return System.Convert.ToBase64String(plainTextBytes);
        }
    }
}

感谢任何帮助。谢谢!

如文档中所述

https://developer.spotify.com/web-api/authorization-guide/

你必须发送

"grant_type"、"code" 和 "redirect_uri" 参数作为 POST 正文。您将它们作为 url 参数发送,因此 Spotify 会给出错误。