3
在项目中使用的MVC4的WebAPI的RC版,我一直遇到的API服务器端以下错误:例外与请求的WebAPI格式化
System.FormatException: The format of value 'application/json; charset=utf-8' is invalid.
我周围不少尝试了我如何“M从客户端调用它,现在用RestSharp像这样:
var client = new RestClient("http://localhost:29874");
var request = new RestRequest("api/submit", Method.POST);
var content = new RestSharp.Serializers.JsonSerializer().Serialize(myDto);
request.RequestFormat = DataFormat.Json;
request.AddBody(content);
var restResponse = client.Execute(request);
var response = restResponse.Content;
凡我在服务器端ApiController名为SubmitController。该SubmitController样子:
public class SubmitController : ApiController
{
public SubmitResponse Post(SomeDtoType dto)
{
var response = new SubmitResponse();
// do something interesting with the dto;
return response;
}
}
当然,控制方法永远不会被调用,因为我得到了一格式例外,我在Global.asax中的服务器上捕获的Application_Error()出来:
protected void Application_Error()
{
var ex = Server.GetLastError();
if (ex != null)
{
if (ex is HttpUnhandledException)
{
ex = ex.InnerException;
}
logger.Error("Unhandled error. ", ex);
}
}
我没有为WebAPI服务器代码定义任何自定义格式化程序。我错过了什么?
编辑:有些东西是严重的错误,因为当我换成XML而不是JSON时,我遇到了完全相同的问题。
这也是我的解决方案。 – Galen 2013-01-24 01:14:10