WebApi 通过拦截器设置特定的返回格式

  

public class ActionFilter : ActionFilterAttribute

         /// <summary>

        /// Action执行之后由MVC框架调用
        /// </summary>
        /// <param name="actionExecutedContext"></param>
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            var requestUrl = actionExecutedContext.Request.RequestUri.AbsolutePath;
            if (requestUrl.Equals("/api/restful/order") && actionExecutedContext.Response != null
              && actionExecutedContext.Response.StatusCode == HttpStatusCode.OK)
            {
        //获取原始返回结果 var datastr = actionExecutedContext.ActionContext.Response.Content.ReadAsAsync<object>().Result;
//定义需要返回的格式类型 var responseModel = new ResponseModel() { errormsg = "", requestId = ((Titan.Api.Web.Outside.RESTful.Model.ExtApiResultBase)datastr).RequestId }; HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(JsonConvert.SerializeObject(responseModel), Encoding.GetEncoding("UTF-8"), "application/json") }; actionExecutedContext.Response = result; } base.OnActionExecuted(actionExecutedContext); }  
}

最后需要在Global中配置     config.Filters.Add(new ActionFilter());

posted @ 2018-09-28 12:35  爱坐枫林晚  阅读(1059)  评论(0编辑  收藏  举报