我正在尝试与REST服务进行通信,并且试图调用一种POST方法,该方法需要在文章正文中提供一些数据。
我的模型课都很好地设置了以下内容:
public class MyRequestClass
{
public string ResellerId { get; set; }
public string TransactionId { get; set; }
... other properties of no interest here ...
}
Run Code Online (Sandbox Code Playgroud)
并且我在C#中使用RestSharp来调用我的REST服务,如下所示:
RestClient _client = new RestClient(someUrl);
var restRequest = new RestRequest("/post-endpoint", Method.POST);
restRequest.RequestFormat = DataFormat.Json;
restRequest.AddHeader("Content-Type", "application/json");
restRequest.AddJsonBody(request); // of type "MyRequestClass"
IRestResponse<MyResponse> response = _client.Execute<MyResponse>(restRequest);
Run Code Online (Sandbox Code Playgroud)
一切似乎都正常运行-没有异常抛出。但是该服务将响应:
我们在处理您的请求时遇到问题
当我查看正在发送的请求JSON时,我看到所有属性都使用大写字母拼写:
{ "ResellerId":"123","TransactionId":"456" }
Run Code Online (Sandbox Code Playgroud)
这就是问题所在-该服务将所有小写字母排除在外:
{ "resellerId":"123","transactionId":"456" }
Run Code Online (Sandbox Code Playgroud)
因此,我尝试使用属性装饰C#模型类:
public class MyRequestClass
{
[RestSharp.Serializers.SerializeAs(Name = "resellerId")]
public string ResellerId { get; set; }
[RestSharp.Serializers.SerializeAs(Name = "transactionId")]
public string TransactionId { get; set; }
... other properties of no interest here ...
}
Run Code Online (Sandbox Code Playgroud)
但这似乎并没有改变任何内容-JSON请求窗台在大写字母拼写中包含属性名称,因此调用失败。
如何告诉RestSharp 在C#模型类生成的JSON中始终使用小写属性名称?
编辑:这个答案已经过时了。阅读@marc_s 共享的线程。我不会删除这个答案,因为它曾经很有帮助。
您可以或者应该将 Json.NET 添加到 RestSharp。
RestSharp 的 github 存储库上有一个关于此的问题。