2

当我以编程方式向令牌端点请求访问令牌时,我收到“错误请求:无效响应”。参数需要作为 x-www-formurlencoded 传递

这是我的代码:

[FunctionName("GetAccessToken")]
    public async Task<IActionResult> GetAccessToken(
  [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
  ILogger log)
    {
        try
        {
            log.LogInformation("C# HTTP trigger function ''GetAccessToken'' processed a request.");

            string clientSecret = "secret";

            string accessToken = "";     

            RequestAccessToken rT = new RequestAccessToken();
            rT.Code = req.Form["code"];
            rT.RedirectUri = req.Form["redirect_uri"];
            rT.GrantType = req.Form["grant_type"];
            rT.ClientId = req.Form["client_id"];
            rT.CodeVerifier = req.Form["code_verifier"];
            //rT.Scope = req.Form["scope"];

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://<base_uri>");
                

                //client.DefaultRequestHeaders
                //.Accept
                //.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));//ACCEPT header
                

                var body = new { EntityState = new {
                    code = rT.Code,
                    redirect_uri = rT.RedirectUri,
                    grant_type = rT.GrantType,
                    client_id = rT.ClientId,
                    client_secret = clientSecret,
                    code_verifier = rT.CodeVerifier,
                    

                } }.ToString();


                var data = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded");

                var result = await client.PostAsJsonAsync(
                               "/login",
                               body);
                accessToken = await result.Content.ReadAsStringAsync();
            }             

            return new OkObjectResult(accessToken);

        }
        catch (Exception ex)
        {
            log.LogInformation(ex.ToString());

            return new ObjectResult(ex.ToString()) { StatusCode = 500 };
        }
    }

这是来自 react 应用程序的调用: 在此处输入图像描述

你能告诉我我哪里错了吗?或者给我一个例子?

新建议版本:

[FunctionName("GetAccessToken")]
    public async Task<IActionResult> GetAccessToken(
  [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
  ILogger log)
    {
        try
        {
            log.LogInformation("C# HTTP trigger function ''GetAccessToken'' processed a request.");

            string clientSecret = "secret";

            string accessToken = "";
            HttpResponseMessage response = null;

            RequestAccessToken rT = new RequestAccessToken();
            rT.Code = req.Form["code"];
            rT.RedirectUri = req.Form["redirect_uri"];
            rT.GrantType = req.Form["grant_type"];
            rT.ClientId = req.Form["client_id"];
            rT.CodeVerifier = req.Form["code_verifier"];
            //rT.Scope = req.Form["scope"];

           

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://<base_uri>");
               

                requestObject.Add("code", rT.Code);
                requestObject.Add("redirect_uri", rT.RedirectUri);
                requestObject.Add("grant_type", rT.GrantType);
                requestObject.Add("client_id", rT.ClientId);
                requestObject.Add("client_secret", clientSecret);
                requestObject.Add("code_verifier", rT.CodeVerifier);


                var boundary = Guid.NewGuid().ToString();
                using (var multiForm = new MultipartFormDataContent(boundary))
                {
                    foreach (var keyValuePair in (Dictionary<string, string>)requestObject)
                    {
                        multiForm.Add(new StringContent(keyValuePair.Value), String.Format("\"{0}\"", keyValuePair.Key));
                    }

                    response = client.PostAsync("/login", multiForm).Result;
                }


            }             

            return new OkObjectResult(accessToken);

        }
        catch (Exception ex)
        {
            log.LogInformation(ex.ToString());

            return new ObjectResult(ex.ToString()) { StatusCode = 500 };
        }
    }
4

1 回答 1

0

而不是 PostAsJsonAsync 使用 MultipartFormDataContent 和 PostAsync,如下所示:

var boundary = Guid.NewGuid().ToString();
using (var multiForm = new MultipartFormDataContent(boundary))
{
   foreach (var keyValuePair in (Dictionary<string, string>)requestObject)
   {
        multiForm.Add(new StringContent(keyValuePair.Value), String.Format("\"{0}\"", keyValuePair.Key));
   }

   response = client.PostAsync(url, multiForm).Result;
}

如果都是字符串值,最好在字典中创建您的请求。或者您可以根据您的要求进行更改。

于 2020-09-03T07:39:09.367 回答