【发布时间】:2015-07-21 16:16:00
【问题描述】:
我有一个简单的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 重载触发。
可能出了什么问题?
【问题讨论】:
标签: c# asp.net-web-api deserialization asp.net-web-api2 mediatypeformatter