使用RestSharp调用POST时获取BadRequest

时间:2016-12-30 12:01:16

标签: c# json restsharp

跟进我的问题Getting null values when deserializing a list using 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"}}

我应该更改/添加什么才能让它发挥作用? (我得到了在SoapUI中工作的请求)

2 个答案:

答案 0 :(得分:0)

您很可能也必须在请求中添加Content-Type-header:

request.AddHeader("Content-Type", "application/json; charset=utf-8");

还要看看here。希望也有帮助。

答案 1 :(得分:0)

我自己解决了。可能不是最漂亮的解决方案,但改变我的代码就像这样:

    Email jsonElement = new Email();
    jsonElement.Evstatus = "processed";
    EmailObj jsonBody = new EmailObj();
    jsonBody.email = jsonElement;
    request.AddJsonBody(jsonBody);