首页 > 解决方案 > OAuth2 + 生成新的授权承载访问令牌 C# MVC

问题描述

任何人都可以帮我在 C# MVC 中生成访问令牌。

PostMan 访问令牌生成

下面的代码在控制台应用程序中工作正常但它在 MVC c# 中不起作用,因为“无法解析 URL”而出现错误

 static void Main(string[] args)  {
       Console.WriteLine("Starting ...");
        DoIt().Wait();
        Console.ReadLine();
    }
 private static async Task<string> DoIt()     {

        accessToken = await GetAccessToken();

return accessToken;
    }

    private static async Task<string> GetAccessToken()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(baseUrl);

            // We want the response to be JSON.
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            // Build up the data to POST.
            List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>();
            postData.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
            postData.Add(new KeyValuePair<string, string>("client_id", "clientId"));
            postData.Add(new KeyValuePair<string, string>("client_secret", "clientSecret"));
            postData.Add(new KeyValuePair<string, string>("access_token_url", "Access Token URL"));

            FormUrlEncodedContent content = new FormUrlEncodedContent(postData);

            // Post to the Server and parse the response.
            HttpResponseMessage response = client.PostAsync("Token", content).Result;
            string jsonString = await response.Content.ReadAsStringAsync();
            object responseData = JsonConvert.DeserializeObject(jsonString);

            // return the Access Token.
            return ((dynamic)responseData).access_token;
        }
    }

标签: c#asp.net-mvcpostman

解决方案


推荐阅读