【问题标题】:Postman generated code get {"error":"invalid_client"} on C# consolePostman 生成的代码在 C# 控制台上获取 {"error":"invalid_client"}
【发布时间】:2021-01-22 23:02:09
【问题描述】:

我已将 Postman 代码生成器的粘贴“获取令牌”请求表单复制到 C# 我在 Postman 中获得了令牌,但在 Visual Studio 上它给出了 {"error":"invalid_client"} 而所有细节都是相同的。它现在使用 RestClient。我想将其转换为 HttpClient 并检查一下。感谢您的帮助。

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RestSharp;

namespace ConsoleApp_postman_copyPaste_test
{
    class Program
    {
        static void Main(string[] args)
        {
            //Direct from Postman
            var client = new RestClient("https://label.xxx.xxx.net/mytoken++++/api/label/v1/auth/token");
            client.Timeout = -1;
            var request = new RestRequest(Method.GET);
            request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            request.AddParameter("grant_type", "password");
            request.AddParameter("client_id", "0000f-c111-41b2-a90b-959aa839db65");
            request.AddParameter("Username", "aaa19 llcfrt");
            request.AddParameter("Password", "gb&8HJtyKB");
            IRestResponse response = client.Execute(request);
            Console.WriteLine(response.Content);

            //up to here from postman

            Trace.TraceInformation(response.Content);
        }
    }
}


【问题讨论】:

  • 您应该将grant_type 和client_id 添加为标头,而不是请求参数。
  • 试过了,不行。代码取自 Postman,但实际上在 postman 上,这些是作为正文插入的(并且工作顺利),但我不确定如何在代码中实现。
  • 该请求在 Postman 上工作正常吗?
  • 效果很好,是的 - 我得到了带有令牌的 json

标签: c# api web postman


【解决方案1】:

使请求成为 HTTP Post

static void Main(string[] args)
        {
            //Direct from Postman
            var client = new RestClient("https://label.xxx.xxx.net/mytoken++++/api/label/v1/auth/token");
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            request.AddParameter("grant_type", "password");
            request.AddParameter("client_id", "0000f-c111-41b2-a90b-959aa839db65");
            request.AddParameter("Username", "aaa19 llcfrt");
            request.AddParameter("Password", "gb&8HJtyKB");
            IRestResponse response = client.Execute(request);
            Console.WriteLine(response.Content);

            //up to here from postman

            Trace.TraceInformation(response.Content);
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 2012-08-14
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多