Asp.net

在 Web API / APIController 中控制序列化

  • September 1, 2016

在哪裡可以在 ASP.NET Web API 中指定自定義序列化/反序列化?

我們應用程序的吞吐量需要消息的快速序列化/反序列化,因此我們需要嚴格控制這部分程式碼,以使用我們的自製軟體或 OSS。

我已經檢查了各種來源,例如解釋如何創建自定義值提供者的各種來源,但我還沒有看到一個解釋端到端過程的範例。

任何人都可以指導/向我展示序列化傳入/傳出消息的方式嗎?

還感謝 Web API 中類似於WCF的各種注入點/事件接收器的圖表!

您正在尋找的擴展點是 MediaTypeFormatter。它控制從請求正文讀取和寫入響應正文。這可能是編寫自己的格式化程序的最佳資源:

http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters

這是上面答案中的連結失效的程式碼範例

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());
   }

希望這可以節省您一些時間。

引用自:https://stackoverflow.com/questions/14145097