2012-08-16 88 views
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时,我遇到了完全相同的问题。

回答

3

在此添加此项,因为其他人可能会觉得它有用。

我使用的WebAPI组件版本是4.0.20505.x,我确实遇到了问题。

昨天,新版本发布在NuGet上,版本4.0.20710.0,现在可以完美地与上面的代码一起工作。

+0

这也是我的解决方案。 – Galen 2013-01-24 01:14:10