3

在项目中使用 RC 版本的 MVC4 WebAPI,我在 API 服务器端一直遇到以下错误:

System.FormatException: The format of value 'application/json; charset=utf-8' is invalid.

我已经尝试了很多关于如何从客户端调用它的方法,现在使用 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 时,我遇到了完全相同的问题。

4

1 回答 1

3

在此处添加此内容,因为其他人可能会发现它很有用。

The version of the WebAPI components that I was using were 4.0.20505.x, where I most certainly had a problem.

Yesterday, the new versions were posted on NuGet, version 4.0.20710.0, which now works with the code above flawlessly.

于 2012-08-16T16:16:24.323 回答