按原廠設定, 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) { ...
Leave a Reply