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超載觸發。
什麼可能是錯的?