RestSharp post 请求 - 具有 x-www-form-urlencoded 值的正文

RestSharp post request - Body with x-www-form-urlencoded values

我正在使用 postman 并发出 api post 请求,其中我使用 x-www-form-urlencoded key/values 添加正文并且它工作正常在 postman.

当我使用 RestSharp 包从 C# 尝试时出现了问题。

我尝试了下面的代码但没有得到响应。我收到 "BadRequest" invalid_client 错误。

public class ClientConfig {
    public string client_id { get; set; } = "value here";
    public string grant_type { get; set; } = "value here";
    public string client_secret { get; set; } = "value here";
    public string scope { get; set; } = "value here";
    public string response_type { get; set; } = "value here";
}

public void GetResponse() {
        var client = new RestClient("api-url-here");
        var req = new RestRequest("endpoint-here",Method.POST);
        var config = new ClientConfig();//values to pass in request

        req.AddHeader("Content-Type","application/x-www-form-urlencoded");
        req.AddParameter("application/x-www-form-urlencoded",config,ParameterType.RequestBody);

        var res = client.Execute(req);
        return;
    }

//Also tried this

    req.AddParameter("client_id",config.client_id,"application/x-www-form-urlencoded",ParameterType.RequestBody);
                req.AddParameter("grant_type",config.grant_type,"application/x-www-form-urlencoded",ParameterType.RequestBody);
                req.AddParameter("client_secret",config.client_secret,"application/x-www-form-urlencoded",ParameterType.RequestBody);
                req.AddParameter("scope",config.scope,ParameterType.RequestBody);
                req.AddParameter("response_type",config.response_type,"application/x-www-form-urlencoded",ParameterType.RequestBody);

//tried this too
var client = new RestClient("url-here");
            var req = new RestRequest("endpointhere",Method.POST);
            var config = new ClientConfig();
req.AddBody(config);
var res = client.Execute(req);

这对我有用,它是邮递员的生成器

        var token = new TokenValidation()
        {
               app_id = CloudConfigurationManager.GetSetting("appId"),
               secret = CloudConfigurationManager.GetSetting("secret"),
               grant_type = CloudConfigurationManager.GetSetting("grant_type"),
               Username = CloudConfigurationManager.GetSetting("Username"),
               Password = CloudConfigurationManager.GetSetting("Password"),
        };

        var client = new RestClient($"{xxx}{tokenEndPoint}");
        var request = new RestRequest(Method.POST);
        request.AddHeader("content-type", "application/x-www-form-urlencoded");
        request.AddParameter("application/x-www-form-urlencoded", $"app_id={token.app_id}&secret={token.secret}&grant_type={token.grant_type}&Username={token.Username}&Password={token.Password}", ParameterType.RequestBody);
        IRestResponse response = client.Execute(request);

        if (response.StatusCode != HttpStatusCode.OK)
        {
            Console.WriteLine("Access Token cannot obtain, process terminate");
            return null;
        }

        var tokenResponse = JsonConvert.DeserializeObject<TokenValidationResponse>(response.Content);

我个人认为这种方式在发送 Form-UrlEncoded 数据时更适合我。

public void GetResponse() {
        var client = new RestClient("api-url-here");
        var req = new RestRequest("endpoint-here",Method.POST);
        var config = new ClientConfig();//values to pass in request

        // Content type is not required when adding parameters this way
        // This will also automatically UrlEncode the values
        req.AddParameter("client_id",config.client_id, ParameterType.GetOrPost);
        req.AddParameter("grant_type",config.grant_type, ParameterType.GetOrPost);
        req.AddParameter("client_secret",config.client_secret, ParameterType.GetOrPost);
        req.AddParameter("scope",config.scope, ParameterType.GetOrPost);
        req.AddParameter("response_type",config.response_type, ParameterType.GetOrPost);

        var res = client.Execute(req);
        return;
}

有关此参数类型的详细信息,请参见此处: https://github.com/restsharp/RestSharp/wiki/ParameterTypes-for-RestRequest#getorpost

就我个人而言,我发现 AddObject() 方法非常有用,而且当您要添加如此多的参数时更清晰。

public void GetResponse() {
        var client = new RestClient("api-url-here");
        var req = new RestRequest("endpoint-here",Method.POST);
        var config = new ClientConfig();//values to pass in request

        req.AddHeader("Content-Type","application/x-www-form-urlencoded");
        req.AddObject(config);

        var res = client.Execute(req);
        return res;
    }

在我的例子中,这是有效的

req.AddParameter("client_id", "unigen-corporation", ParameterType.HttpHeader);
req.AddParameter("grant_type", "client_credentials", ParameterType.GetOrPost);

如果它在 postman 上有效,您只需按右侧的代码按钮即可。这将提供多种语言的工作示例。它是信息图标上方的按钮。我会 post 截图,但我没有 10 声望。

如果您从邮递员那里复制了代码,请尝试删除以下内容:

request.AlwaysMultipartFormData = true;

在我的例子中,删除此行代码后有效。

var client1 = new RestClient(URI);
var request1 = new RestRequest(Method.POST);
request1.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request1.AddParameter("client_id", "XX");
request1.AddParameter("client_secret", "XX");
request1.AddParameter("grant_type", "XX");
request1.AddParameter("role", "XX");
IRestResponse response1 = client1.Execute(request1);
System.Console.WriteLine(response1.Content);

根据需要添加参数。这个工作很好!