Upgrading to MVC4 RC: No MediaTypeFormatter is available to read an object of type 'TestRequestModel' from content with media type ''undefined''

…衆ロ難τιáo~ 提交于 2019-11-28 12:11:26

I see your original question was answered, but to answer the other one, Model binding has changed somewhat in the RC.

http://weblogs.thinktecture.com/cweyer/2012/06/aspnet-web-api-changes-from-beta-to-rc.html

This link has some details about it. But to sum up the change that appears to be affecting you, Model binding pulls its values from either the body, or the uri of the request. This is true for previous releases as well, but with the release candidate, MVC4 will, by default, look to the body for complex types, and the uri for value types.

So, if you submit a body with your request containing the "SomeParameter" key, you should see it bind. Or you could bind with the url if you change the declaration to:

 public TestModel Get(int? someParameter)
 {

 }

Thankfully, the team foresaw the potential problems with this and left us with attributes we could use to override this behavior.

 public TestModel Get([FromUri]TestRequestModel request)
 {

 }

The key here is the [FromUri] which tells the model binder to look in the uri for the values. There is also [FromBody] if you want to put a value type in the body of a request.

We were seeing the same thing. In our case the problem was a complex object being passed into a get method. We needed to add a [FromUri] attribute in the parameter to that method.

http://forums.asp.net/t/1809925.aspx/1?GET+requests+with+complex+object+as+input+parameter

public class SearchController : ApiController
{
    // added [FromUri] in beta to RC transition otherwise media type formatter error
    public IQueryable<SearchResultEventModel> Get( [FromUri]SearchSpecModel search )
    {
        // ...
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!