使用 RestSharp 调用 POST 时获取 BadRequest
Getting BadRequest when calling POST with RestSharp
跟进我的问题
我现在还有一个问题。我需要调用 POST 并且 json 正文应该如下所示:
{"email": {"evstatus": "processed"}}
我的代码是这样的
class Email
{
public string Evexpire { get; set; }
public string Evfields { get; set; }
public string Evsysseq { get; set; }
public string Evtime { get; set; }
public string Evtype { get; set; }
public string Evstatus { get; set; }
}
var client = new RestClient("xxx");
client.Authenticator = new HttpBasicAuthenticator("xx", "x");
var request = new RestRequest("xxxx/action/processed", Method.POST);
request.RequestFormat = DataFormat.Json;
request.RootElement = "email";
request.AddJsonBody(new Email { Evstatus = "processed" } );
但是我收到这个错误:
"StatusCode: BadRequest, Content-Type: application/json;charset=utf-8, Content-Length: 0)"
当我在调试器中查看请求时,我在参数列表中看到了这一点,除了具有空值的字段外,它看起来不像我需要的。
{application/json={"Evexpire":null,"Evfields":null,"Evsysseq":null,"Evtime":null,"Evtype":null,"Evstatus":"processed"}}
我 change/add 应该怎么做才能让它发挥作用? (我收到了在 SoapUI 中工作的请求)
很可能您还必须将 Content-Type-header 添加到请求中:
request.AddHeader("Content-Type", "application/json; charset=utf-8");
也看看here。希望也有帮助。
我自己解决了。可能不是最漂亮的解决方案,但像这样更改我的代码有效:
Email jsonElement = new Email();
jsonElement.Evstatus = "processed";
EmailObj jsonBody = new EmailObj();
jsonBody.email = jsonElement;
request.AddJsonBody(jsonBody);
跟进我的问题
我现在还有一个问题。我需要调用 POST 并且 json 正文应该如下所示:
{"email": {"evstatus": "processed"}}
我的代码是这样的
class Email
{
public string Evexpire { get; set; }
public string Evfields { get; set; }
public string Evsysseq { get; set; }
public string Evtime { get; set; }
public string Evtype { get; set; }
public string Evstatus { get; set; }
}
var client = new RestClient("xxx");
client.Authenticator = new HttpBasicAuthenticator("xx", "x");
var request = new RestRequest("xxxx/action/processed", Method.POST);
request.RequestFormat = DataFormat.Json;
request.RootElement = "email";
request.AddJsonBody(new Email { Evstatus = "processed" } );
但是我收到这个错误:
"StatusCode: BadRequest, Content-Type: application/json;charset=utf-8, Content-Length: 0)"
当我在调试器中查看请求时,我在参数列表中看到了这一点,除了具有空值的字段外,它看起来不像我需要的。
{application/json={"Evexpire":null,"Evfields":null,"Evsysseq":null,"Evtime":null,"Evtype":null,"Evstatus":"processed"}}
我 change/add 应该怎么做才能让它发挥作用? (我收到了在 SoapUI 中工作的请求)
很可能您还必须将 Content-Type-header 添加到请求中:
request.AddHeader("Content-Type", "application/json; charset=utf-8");
也看看here。希望也有帮助。
我自己解决了。可能不是最漂亮的解决方案,但像这样更改我的代码有效:
Email jsonElement = new Email();
jsonElement.Evstatus = "processed";
EmailObj jsonBody = new EmailObj();
jsonBody.email = jsonElement;
request.AddJsonBody(jsonBody);