简体   繁体   English

使用 Razor 页面从回调页面访问 Spotify API 访问令牌

[英]Access Spotify API access token from callback page with Razor Pages

Basically, I have a button that executes the following code基本上,我有一个执行以下代码的按钮

 $(document).ready(function (){
        $("#login-button").click(function () {
            var parameters = "@Model.parameters";
            parameters = parameters.replace(/&/g, "&");
            window.location.href = "https://accounts.spotify.com/authorize/".concat(parameters);
        })
    })

and it successfully gives an access token in https://localhost:44382/Callback#access_token=TOKEN&token_type=Bearer&expires_in=3600&state=586917.它成功地在 https://localhost:44382/Callback#access_token=TOKEN&token_type=Bearer&expires_in=3600&state=586917 中提供了访问令牌。

But I can't figure out how to pull out the access token from the URL so I can use it as a variable.但我不知道如何从 URL 中提取访问令牌,因此我可以将其用作变量。 I tried我试过了

 public IActionResult OnGet()
    {
        @TempData["access_token"] = (string)HttpContext.Request.Query["access_token"];

        return Page();
    }

on the Callback.cshtml.cs file, but it seems to return null(the whole Query contains no elements), because as I suspect, it executes prior to the URL actually containing the token.在 Callback.cshtml.cs 文件上,但它似乎返回 null(整个 Query 不包含任何元素),因为我怀疑它在实际包含令牌的 URL 之前执行。 And also, I tried putting in the following code to Callback.cshtml, but it runs into the same issue.而且,我尝试将以下代码放入 Callback.cshtml,但它遇到了同样的问题。 In addition to the $window.location.href not actually redirecting.除了 $window.location.href 实际上没有重定向。

 $(document).load(function () {
         @TempData["access_token"] = @HttpContext.Request.Query["access_token"];
            $window.location.href = "/Overview";

    })

https://developer.spotify.com/documentation/general/guides/authorization-guide/ https://developer.spotify.com/documentation/general/guides/authorization-guide/

Try adding a variable and declaring So you may need to add an $.ajax call, before the window.location.href.尝试添加一个变量并声明因此您可能需要在 window.location.href 之前添加一个 $.ajax 调用。 .. generic example for brevity (not tested) .. 简洁的通用示例(未测试)


         $(document).ready(function (){
            var url = "https://accounts.spotify.com/authorize/";
            var parameters = "@Model.parameters";
            $("#login-button").click(function () {
            $.ajax({
                url: 'https://api.spotify.com/v1/browse/new-releases',
                type: 'GET',
                headers: {
                    'Authorization' : 'Bearer ' + accessToken
                },
            success: function(response) {
            parameters = parameters.replace(/&/g, "&");
            window.location.href = url.concat(parameters);
                }
            });
          })
       })

Without setting up a test application and diving deep into this, you could also build up your request via c#.无需设置测试应用程序并深入研究,您也可以通过 c# 构建您的请求。 You can still have the ajax call, that simply calls the action method in your controller, but the controll can build up the request.您仍然可以使用 ajax 调用,它只是调用 controller 中的操作方法,但控制器可以建立请求。 Example below....下面的例子......


public IList<SearchResult> GetSpotifyAuthorization(string parameters)
    {
        IList<SearchResult> searchResults = new List<SearchResult>();
        ParseElementViewModel parseElement = new ParseElementViewModel();

        parameters = Regex.Replace(parameters, "[^A-Za-z0-9]", ""); // just an example
        string url = $"https://accounts.spotify.com/authorize/{parameters}? format=json";
        HttpClient client = new HttpClient();

        client.BaseAddress = new Uri(url);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        try
        {
            var request = client.GetAsync(url).Result;
            if (request.IsSuccessStatusCode)
            {
                var res = request.Content.ReadAsStringAsync().Result;
                JObject search = JObject.Parse(res);
                IList<JToken> results = search["Results"].Children().ToList();

                foreach (JToken result in results)
                {
                    SearchResult jsonResults = JsonConvert.DeserializeObject<SearchResult>(result.ToString());
                    searchResults.Add(jsonResults);
                }

            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            return null;
        }
        return searchResults;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM