Asp.net-Mvc

升級到 MVC4 RC:沒有 MediaTypeFormatter 可用於從媒體類型為“未定義”的內容中讀取類型為“TestRequestModel”的對象

  • June 8, 2012

我一直在使用 MVC4 測試版,目前正在努力升級到最近發布的 RC 版本。

似乎模型綁定複雜請求類型已經改變,但我無法弄清楚我做錯了什麼/做錯了什麼。

例如,假設我有以下 API 控制器:

public class HomeApiController : ApiController
{
   public TestModel Get()
   {
       return new TestModel
       {
           Id = int.MaxValue,
           Description = "TestDescription",
           Time = DateTime.Now
       };
   }
}

這產生了預期的結果:

<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>

現在說我只是更改簽名,接受請求類型,如下所示:

public TestModel Get(TestRequestModel request)
{
   ...

public class TestRequestModel
{
   public int? SomeParameter { get; set; }
}

我現在收到以下錯誤:

<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>

我查看了在 中引發此異常的原始碼HttpContentExtensions,但它看起來像是檢查內容標題(我應該有),如果沒有,它會嘗試從MediaTypeFormatter集合中獲取格式化程序它具有特定類型(它不能)然後拋出。

還有其他人經歷過嗎?我缺少一些全球註冊?

我看到您的原始問題已得到回答,但要回答另一個問題,模型綁定在 RC 中有所改變。

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

這個連結有一些關於它的細節。但總結一下似乎影響您的更改,模型綁定從請求的主體或 uri 中提取其值。對於以前的版本也是如此,但是對於候選版本,MVC4 預設情況下會在 body 中查找複雜類型,並在 uri 中查找值類型。

因此,如果您送出的請求中包含“SomeParameter”鍵的正文,您應該會看到它已綁定。或者,如果您將聲明更改為:

public TestModel Get(int? someParameter)
{

}

值得慶幸的是,團隊預見到了這方面的潛在問題,並為我們留下了可以用來覆蓋此行為的屬性。

public TestModel Get([FromUri]TestRequestModel request)
{

}

這裡的關鍵是[FromUri]告訴模型綁定器在 uri 中查找值。[FromBody]如果您想在請求的正文中放置一個值類型,也可以這樣做。

引用自:https://stackoverflow.com/questions/10934077