调用我的WebApi参数的RestSharp为空

时间:2017-02-21 04:36:22

标签: c# asp.net-web-api restsharp

  • RestSharp 105.2.3
  • WebAPI 2

所以我有一个简单的WebApi控制器:

public class EnettController : ApiController
{
    private readonly DebitService _EnettService;

    public EnettController()
    {
        _EnettService = new DebitService();
    }

    [HttpPost]
    public ProcessDirectDebitResponse ProcessDirectDebit([FromBody] ProcessDirectDebitRequest aRequest)
    {
    }
}

从我的测试工具中我用以下RestSharp代码调用它:

RestClient client = new RestClient($"http://{txtHost.Text}:{txtPort.Text}");

ProcessDirectDebitRequest dataForRequest = new ProcessDirectDebitRequest
                                           {
                                               AgentId = "James Bond",
                                               DepartureDate = DateTime.Now,
                                               Version = "123"
                                           };

RestRequest request = new RestRequest("api/Enett", Method.POST)
                      {
                          RequestFormat = DataFormat.Json
                      };
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/json; charset=utf-8");
request.AddBody(dataForRequest);

IRestResponse<ProcessDirectDebitResponse> response = client.Execute<ProcessDirectDebitResponse>(request);

if (response.StatusCode != HttpStatusCode.OK)
{
    MessageBox.Show($"Did not yet a 200 response. Got instead {response.StatusCode}");
}

我的WebAPI终点没问题,但aRequest始终为NULL。所以我错过了一些明显的东西我只是看不出它是什么。为什么aRequest总是为NULL?

1 个答案:

答案 0 :(得分:0)

这里的问题原来是ProcessDirectDebitRequest类被装饰为[Serializable],导致预期有以下有效载荷:

{
  "<AgentId>k__BackingField": "sample string 1",
  "<DepartureDate>k__BackingField": "2017-02-22T12:01:25.8332359+11:00",
  "<Version>k__BackingField": "sample string 3"
}

而不是预期的:

{
  "AgentId": "sample string 1",
  "DepartureDate": "2017-02-22T12:01:25.8332359+11:00",
  "Version": "sample string 3"
}

根据您的需要,有几种方法:

  1. 请勿使用[序列化]
  2. 进行装饰
  3. 使用config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings(); //删除支持字段并保留[序列化]
  4. 明确使用[DataContract],[DataMember]