RestSharp 中的错误请求,但在 Postman 上工作

Bad Resquest in RestSharp, but working on Postman

基本上,我一直在尝试使用 restsharp 在 c# 上通过 oauth2 进行身份验证,但我收到了错误的请求响应,我不确定它是否与 API 配置有关,或者它是否我的代码中缺少一些东西。

public string getToken(string email, string password)
    {
        var restclient = new RestClient(loginUrl);
        RestRequest request = new RestRequest("request/oauth") { Method = Method.GET };
        request.AddHeader("Accept", "application/json");
        request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
        request.AddParameter("email", HttpUtility.UrlPathEncode(email));
        request.AddParameter("password", HttpUtility.UrlPathEncode(password));
        request.AddParameter("grant_type", HttpUtility.UrlPathEncode("password"));
        var tResponse = restclient.Execute(request);
        var responseJson = tResponse.Content;
        string token = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseJson)["access_token"].ToString();
        return token;
    }

这是我执行该代码时的响应

这是邮递员处决

谢谢!

var restclient = new RestClient(loginUrl);我想你需要检查一下你的 url.

我认为以您添加的方式添加参数存在问题。 最新的 restsharp 支持这个,

此外,通过设置为 false

避免对参数进行编码
var request = new RestRequest("resource", Method.GET);
request.AddQueryParameter("email", "test@test.com",false); 

试试这个..你的 OAuth 是密码授予类型你确定你没有丢失任何凭证,如 client_id、范围和 client_secret.

public static string getAccessToken(string usern, string pswd)
        {
            RestClient client = new RestClient(ConfigurationManager.AppSettings["TokenUrl"]);
            RestRequest request = new RestRequest() { Method = Method.GET};

            request.AddParameter("grant_type", "password", ParameterType.GetOrPost);
            request.AddParameter("username", usern, ParameterType.GetOrPost);
            request.AddParameter("password", pswd, ParameterType.GetOrPost);
           

            IRestResponse response = client.Execute(request);
            var responseJson = response.Content;
            var token = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseJson)["access_token"].ToString();


            return token;

        }