0

我有一個簡單MediaTypeFormatter像這樣:定製MediaTypeFormatter不被用於反序列化

public class SomeFormatter : MediaTypeFormatter 
{ 
    public override bool CanReadType(Type type) 
    { 
     return type == typeof(SomeRequest); 
    } 

    public override bool CanWriteType(Type type) 
    { 
     return type == typeof(SomeResponse); 
    } 

    public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger) 
    { 
     return Task.Factory.StartNew(() => 
     { 
      using (readStream) 
      { 
       return (object)new SomeRequest(); 
      } 
     }); 
    } 

    public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger, 
     CancellationToken cancellationToken) 
    { 
     // ReSharper disable once MethodSupportsCancellation 
     return ReadFromStreamAsync(type, readStream, content, formatterLogger); 
    } 

    public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext) 
    { 
     return Task.Factory.StartNew(() => 
     { 
      for (var i = 0; i < 255; i++) 
      { 
       writeStream.WriteByte((byte)i); 
      } 
     }); 
    } 
} 

它是有線在WebApiConfig像這樣:

public static class WebApiConfig 
{ 
    public static void Register(HttpConfiguration config) 
    { 
     // Web API configuration and services 
     config.Formatters.Clear(); 
     config.Formatters.Add(new SomeFormatter()); 

     // Web API routes 
     config.MapHttpAttributeRoutes(); 

     config.Routes.MapHttpRoute(
      name: "DefaultApi", 
      routeTemplate: "api/{controller}/{id}", 
      defaults: new { id = RouteParameter.Optional } 
     ); 
    } 
} 

和一個Web API控制器:

public class SomeController : ApiController 
{ 
    public SomeResponse Get(SomeRequest request) 
    { 
     return new SomeResponse(); 
    } 
} 

但是當我用GET測試控制器(從瀏覽器)時,我得到一個null請求。 CanReadType觸發並返回true,但是沒有任何ReadFromStreamAsync超載觸發。

什麼可能是錯的?

回答

0

這是內容類型頭(或缺少)。

雖然格式化程序被詢問是否能夠反序列化這個Type,但它未能通過下一次檢查,即查看它是否支持提供的內容類型,或者是否未提供內容類型application/octet-stream

所有這一切都需要的是這樣的:

public class SomeFormatter : MediaTypeFormatter 
{ 
    public SomeFormatter() 
    { 
     SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/octet-stream")); 
    } 

... 

}