[C#.NET][Web API] Server 處理自訂格式
除了預設的格式之外,我們還可以替 Web API 加入我們自訂的格式
實作步驟如下:
這不是必要的,但我是用它來實作 Csv 格式,你隨時可以抽換掉這個元件,詳細用法請參考:
http://www.dotblogs.com.tw/yc421206/archive/2012/05/04/71979.aspx
Step2.繼承 MediaTypeFormatter
一定要實作兩個方法:CanWriteType:是否可以將指定類型的物件序列化。CanReadType:是否可以將指定類型的物件反序列化。{ return true; } public override bool CanWriteType(Type type) { return true; }
在建構子裡面加入 MediaTypeHeaderValue("text/csv"):
{ // Add the supported media type. this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/csv")); this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("Application/csv")); this.SupportedEncodings.Add((Encoding)new UTF8Encoding(false, true)); this.SupportedEncodings.Add((Encoding)new UnicodeEncoding(false, true, true)); }
處理 GET request:實作 WriteToStreamAsync,在這裡我使用CsvHelper
TransportContext transportContext) { return Task.Factory.StartNew(() => { Type itemType = type.GetGenericArguments()[0]; using (var stream = new StreamWriter(writeStream)) using (var writer = new CsvWriter(stream)) { writer.WriteHeader(itemType); foreach (var obj in (IEnumerable<object>)value) { writer.WriteRecord(itemType, obj); } stream.Flush(); } }); }{ font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } ]]> 處理 POST request:
實作 ReadFromStreamAsync,在這裡我使用CsvHelper
IFormatterLogger formatterLogger) { return Task.Factory.StartNew(() => { using (var stream = new StreamReader(readStream)) using (var reader = new CsvReader(stream)) { if (!reader.Read()) { return null; } var result = reader.GetRecord(type); return result; } }); }
Step3.設定 Route:
套用我們寫的自訂格式在 WebApiConfig.cs 檔案裡加入config.Formatters.Add(new CsvMediaTypeFormatter()):其餘畫底色的部份請參考http://www.dotblogs.com.tw/yc421206/archive/2013/11/07/127253.aspx{ config.Formatters.JsonFormatter.AddQueryStringMapping("$format", "json", "application/json"); config.Formatters.XmlFormatter.AddQueryStringMapping("$format", "xml", "application/xml"); config.Formatters.XmlFormatter.AddQueryStringMapping("$format", "csv", "text/csv"); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Formatters.Add(new CsvMediaTypeFormatter()); config.EnableSystemDiagnosticsTracing(); var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml"); config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType); }
Step4.測試:
POST:送出格式ISBN,AuthiorName,BookName,Category,Price
1,余小章,Visual Studio2012高級編程,.NET,128看到自定的結果
GET:輸入 api/products 查詢,確認資料有新增很好,有新增了
文章出自:http://www.dotblogs.com.tw/yc421206/archive/2013/11/12/127848.aspx
範例下載:http://yunpan.cn/Q9DQHNdsTD8FW
參考來源:
http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters
若有謬誤,煩請告知,新手發帖請多包涵
Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET