【问题标题】:RestSharp body always emptyRestSharp 身体总是空的
【发布时间】:2022-04-29 21:48:33
【问题描述】:

我需要使用 RestSharp 调用 Post 服务

 var client = new RestClient(url);
 var request = new RestRequest(url,Method.POST);
 request.AddHeader("Content-type", "application/json");
 request.AddJsonBody(new  { grant_type = "client_credentials", client_id = clientIdParam, client_secret = appReg_clientSecret, ressource = _ressource }
               ); 
 var response = client.Post(request);

问题是请求的body始终为null,并且json body作为参数添加

有什么想法吗?

【问题讨论】:

  • 您使用的是什么版本的 RestClient?你检查过参数吗?
  • 版本:106.11.4 。它在参数数组中添加了一个额外的“{=”,即 {={ grant_type = client_credentials, client_id: ....}}
  • 这就是在 c# 中单个 { 的转义方式。您在执行过程中看到什么错误?它不会发送您通过AddJsonBody 添加的json正文吗
  • 错误是正文中缺少“grant_type”。
  • 我建议尝试 client.Execute(request) 看看是否有什么不同

标签: c# .net rest restsharp


【解决方案1】:

https://login.microsoftonline.com/{{tenantId}}/oauth2/token 似乎不接受 json,即使内容类型设置为“application/json”

我的解决方案:

var client = new RestClient("https://login.microsoftonline.com");
var request = new RestRequest("/{{tenantId}}/oauth2/token", Method.POST);

var requestBody = $"grant_type=client_credentials&client_id={clientIdParam}&client_secret={appReg_clientSecret}&resource={_resource}";

request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", requestBody, ParameterType.RequestBody);

var response = client.Execute(request);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-26
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多