Exceptions with WebAPI Request Formatting

人走茶凉 提交于 2019-12-10 10:15:21

问题


Using the RC version of the MVC4 WebAPI in a project, I keep encountering the following error on the API server side:

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

I've experimented around quite a bit with how I'm calling it from the client side, now using RestSharp like so:

     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;

Where my ApiController on the server side is named SubmitController. The SubmitController looks like:

public class SubmitController : ApiController
{
    public SubmitResponse Post(SomeDtoType dto)
    {
        var response = new SubmitResponse();
        // do something interesting with the dto;

        return response;
    }
}

Of course, the controller method is never called, as I get the previous formatting exception, which I'm capturing out of Application_Error() in Global.asax on the server:

  protected void Application_Error()
    {
        var ex = Server.GetLastError();
        if (ex != null)
        {
            if (ex is HttpUnhandledException)
            {
                ex = ex.InnerException;
            }

            logger.Error("Unhandled error.  ", ex);
        }
    }

I do not have any custom formatters defined for the WebAPI server code. What am I missing?

EDIT: Something is seriously amiss, as when I swap out to XML instead of JSON, I get exactly the same issue.


回答1:


Adding this here, as others may find it useful.

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.



来源:https://stackoverflow.com/questions/11988027/exceptions-with-webapi-request-formatting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!