在Web API / APIController中控制序列化

9
我在ASP.NET Web API中哪里可以指定自定义序列化/反序列化?
我们的应用程序吞吐量要求消息快速序列化/反序列化,因此我们需要严密控制代码的这一部分,以使用我们自己的自制方案或外部开源方案。
我已经查看了各种来源,比如this,它解释了如何创建自定义值提供程序,但是我还没有看到一个完整的过程示例。
有人能指导/展示我序列化传入/传出消息的方法吗?
同时,类似于WCF的此处中的Web API中的各种注入点/事件接收器的图表也会很有帮助!

实现 ISerializable 接口? - Robert Harvey
嗯...不,那似乎是使用WCF的方式。 - Alwyn
2个回答

7

看起来就是这样了,虽然每个主机似乎只有一个序列化程序,但是否有一种方法可以在控制器/操作级别上配置此序列化程序呢? - Alwyn
这是可以做到的。你有几种处理方式:1)在创建响应时,你可以明确指定要使用哪个格式化程序。你可以使用Request.CreateResponse扩展方法来选择要使用的格式化程序。或者2)你可以使用每个控制器的配置来自定义特定控制器的格式化程序。 - Youssef Moussaoui
2
这里有一份关于WebAPI可扩展性的好文档:http://www.asp.net/web-api/overview/extensibility/configuring-aspnet-web-api。特别是,它解释了我刚提到的每个控制器配置。 - Youssef Moussaoui

1
以下是一个代码示例,以防上面的链接失效。
public class MerlinStringMediaTypeFormatter : MediaTypeFormatter
{
    public MerlinStringMediaTypeFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
    }

    public override bool CanReadType(Type type)
    {
        return type == typeof (YourObject); //can it deserialize
    }

    public override bool CanWriteType(Type type)
    {
        return type == typeof (YourObject); //can it serialize
    }

    public override Task<object> ReadFromStreamAsync( 
        Type type, 
        Stream readStream, 
        HttpContent content, 
        IFormatterLogger formatterLogger)
    {
        //Here you put deserialization mechanism
        return Task<object>.Factory.StartNew(() => content.ReadAsStringAsync().Result);
    }

    public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
    {
        //Here you would put serialization mechanism
        return base.WriteToStreamAsync(type, value, writeStream, content, transportContext);
    }
}

然后您需要在Global.asax中注册您的格式化程序。

protected void Application_Start()
    {
        config.Formatters.Add(new MerlinStringMediaTypeFormatter());
    }

希望这能为您节省一些时间。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接