[ASP.net MVC] Web API 傳回JSON

按原廠設定, ASP.net MVC 的API Controller 會以XML傳回資料. 但在Front-end 中要處理資料倒困難. 而其實可以透過加入Attribute 使其傳回JSON. 方法如下.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Web;
using System.Web.Http.Filters;

    public class JsonOutputAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            ObjectContent content = actionExecutedContext.Response.Content as ObjectContent;
            var value = content.Value;
            Type targetType = actionExecutedContext.Response.Content.GetType().GetGenericArguments()[0];

            var httpResponseMsg = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                RequestMessage = actionExecutedContext.Request,
                Content = new ObjectContent(targetType, value, new JsonMediaTypeFormatter(), (string)null)
            };

            actionExecutedContext.Response = httpResponseMsg;
            base.OnActionExecuted(actionExecutedContext);
        }
    }

叫用方法:

[JsonOutput]
    public class TestController : ApiController
    {
        [AllowCrossSiteJson]
        public IEnumerable<object> get([FromUri] DateTime startDate, [FromUri] DateTime endDate) {
...

 

About C.H. Ling 262 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.