繁体   English   中英

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;
    }

这是我执行该代码时的响应restsharp执行 在此处输入图像描述

这是postman执行

邮递员处决

谢谢!

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

此外,通过设置为false来避免参数编码

var request = new RestRequest("resource", Method.GET);
request.AddQueryParameter("email", "test@test.com",false); 

var restclient = new RestClient(loginUrl); 我认为您需要检查您的 url。

试试这个.. 你 OAuth 是密码授予类型,你确定你没有丢失任何凭据,如client_id、scope 和 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;

        }

暂无
暂无

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

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