• 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());

  • 相关阅读:
    抽象工厂模式
    工厂方法模式
    单例模式
    适配器模式
    外观模式
    简单工厂模式
    设计模式开篇闲谈
    android ui更新
    android获取Context
    android 事件绑定
  • 原文地址:https://www.cnblogs.com/sunqiang/p/9717944.html
Copyright © 2020-2023  润新知