我有一个简单的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 :(得分:0)
这是内容类型标题(或缺少)。
虽然询问格式化程序是否能够反序列化此Type
,但它未能通过下一次检查,即查看它是否支持所提供的内容类型,或者如果它未提供,{{1 }}
所需要的只是:
application/octet-stream