Bra*_*ton 8 asp.net-mvc model-binding asp.net-mvc-4 asp.net-web-api
我一直在使用MVC4测试版,目前正在努力升级到最近发布的RC版本.
似乎模型绑定复杂请求类型已经改变,但我无法弄清楚我是怎么做错的.
例如,假设我有以下API控制器:
public class HomeApiController : ApiController
{
public TestModel Get()
{
return new TestModel
{
Id = int.MaxValue,
Description = "TestDescription",
Time = DateTime.Now
};
}
}
Run Code Online (Sandbox Code Playgroud)
这产生了预期的结果:
<TestModel xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/xxxx">
<Description>TestDescription</Description>
<Id>2147483647</Id>
<Time>2012-06-07T10:30:01.459147-04:00</Time>
</TestModel>
Run Code Online (Sandbox Code Playgroud)
现在说我只是更改签名,接受请求类型,如下所示:
public TestModel Get(TestRequestModel request)
{
...
public class TestRequestModel
{
public int? SomeParameter { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我现在收到以下错误:
<Exception xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/System.Web.Http.Dispatcher">
<ExceptionType>System.InvalidOperationException</ExceptionType>
<Message>
No MediaTypeFormatter is available to read an object of type 'TestRequestModel' from content with media type ''undefined''.
</Message>
<StackTrace>
at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger) at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger) at System.Web.Http.ModelBinding.FormatterParameterBinding.ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) at System.Web.Http.Controllers.HttpActionBinding.<>c__DisplayClass1.<ExecuteBindingAsync>b__0(HttpParameterBinding parameterBinder) at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext() at System.Threading.Tasks.TaskHelpers.IterateImpl(IEnumerator`1 enumerator, CancellationToken cancellationToken)
</StackTrace>
</Exception>
Run Code Online (Sandbox Code Playgroud)
我已经查看了抛出此异常的源代码HttpContentExtensions,但看起来它检查内容标题(我应该有),如果没有,它会尝试从MediaTypeFormatter集合中获取格式化程序它具有特定类型(它不能)然后抛出.
有人经历过这个吗?我错过了一些全球注册?
小智 13
我看到你原来的问题得到了解答,但为了回答另一个问题,模型绑定在RC中有所改变.
http://weblogs.thinktecture.com/cweyer/2012/06/aspnet-web-api-changes-from-beta-to-rc.html
这个链接有一些关于它的细节.但是为了总结看起来对您有影响的变化,模型绑定从请求的主体或uri中提取其值.对于以前的版本也是如此,但是对于发布候选版本,默认情况下,MVC4将查找正文的复杂类型,以及值类型的uri.
因此,如果您提交包含"SomeParameter"键的请求的正文,您应该看到它绑定.或者,如果将声明更改为以下内容,则可以使用url绑定:
public TestModel Get(int? someParameter)
{
}
Run Code Online (Sandbox Code Playgroud)
值得庆幸的是,该团队预见到了这方面的潜在问题,并为我们留下了可用于覆盖此行为的属性.
public TestModel Get([FromUri]TestRequestModel request)
{
}
Run Code Online (Sandbox Code Playgroud)
这里的关键是[FromUri]告诉模型绑定器在uri中查找值.还有[FromBody],如果你想要把一个值类型的请求的主体.
| 归档时间: |
|
| 查看次数: |
7159 次 |
| 最近记录: |