【问题标题】:Custom MediaTypeFormatter not being used for deserialization自定义 MediaTypeFormatter 未用于反序列化
【发布时间】: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


    【解决方案1】:

    这是内容类型标题(或缺少)。

    虽然询问了格式化程序是否能够反序列化这个Type,但它没有通过下一次检查,即查看它是否支持提供的内容类型,或者如果它没有提供,application/octet-stream。

    只需要这样:

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

    【讨论】:

      猜你喜欢
      • 2020-10-14
      • 1970-01-01
      • 1970-01-01
      • 2016-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-10
      相关资源
      最近更新 更多