手動傳回 JSON 或任何格式的內容
有時候,Web API 的傳回結果不是 JSON,例如我們可能需要傳回一些純文字,甚至圖片或任何二進位檔案。此時就會需要跳過自動序列化的機制,使用我們自行建立的內容來傳回前端。
碰到這種情形,我們可以將 Web API 方法的回傳型別宣告為 HttpResponseMessage。參考以下範例:
using System.Collections.Generic; using System.Net.Http.Headers; using System.Web.Http; using NewtonSoft.Json; namespace MvcAppDemo1.Controllers.Api { public class TestJsonController : ApiController { [HttpGet, HttpPost] // 讓此方法可同時接受 HTTP GET 和 POST 請求. public HttpResponseMessage HandMadeJson() { var data = new Dictionary<string, string>() { // 略 } string json = JsonConvert.SerializeObject(data); var result = new HttpResponseMessage(HttpStatusCode.OK); result.Content = new StringContent(json); result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); return result; } } }
由於是傳回文字內容,所以這裡是用 StringContent 來建立內容物件。
透過這種方式,即使沒有像 [Tip 2] 的額外處理,我們的 Web API 仍然可以傳回 JSON 字串,甚至任何格式的內容。例如底下的程式片段可傳回一個 jpeg 圖片:
var result = new HttpResponseMessage(HttpStatusCode.OK); result.Content = new ByteArrayContent(imageData); result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg"); return result;
由於要傳回的圖片是二進位格式的資料,故建立內容時用的是 ByteArrayContent。它是 StringContent 的父類別。
除了 ByteArrayContent,還有 MultipartContent 和 StreamContent,這個三類別的父親都是 System.Net.Http.HttpContent。
資料來源: https://www.huanlintalk.com/2013/01/aspnet-web-api-and-json.html
留言
張貼留言