1. 程式人生 > >WebApi利用ActionFilterAttribute重新封裝返回結果

WebApi利用ActionFilterAttribute重新封裝返回結果

WebApi利用ActionFilterAttribute重新封裝返回結果


先建立要返回的結果型別:
    /// <summary>
    /// 返回型別
    /// </summary>
    public class ApiResultModel
    {
        private HttpStatusCode statusCode;
        private object data;
        private string errorMessage;
        private bool isSuccess;

        /// <summary>
        /// 狀態程式碼
        /// </summary>
        public HttpStatusCode StatusCode
        {
            get { return statusCode; }
            set { statusCode = value; }
        }

        /// <summary>
        /// 返回的資料
        /// </summary>
        public object Data
        {
            get { return data; }
            set { data = value; }
        }

        /// <summary>
        /// 錯誤訊息
        /// </summary>
        public string ErrorMessage
        {
            get { return errorMessage; }
            set { errorMessage = value; }
        }

        /// <summary>
        /// 是否成功
        /// </summary>
        public bool IsSuccess
        {
            get { return isSuccess; }
            set { isSuccess = value; }
        }
    }

然後建立重寫ActionFilterAttribute下的OnActionExecuted(執行action之後):

先建一個類名字隨意如:ApiResultAttribute繼承於System.Web.Http.Filters.ActionFilterAttribute詳細程式碼如下:

以下程式碼需注意要引用using System.Net.Http否則ReadAsAsync不能使用

public class ApiResultAttribute : System.Web.Http.Filters.ActionFilterAttribute
    {
        public  override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {           base.OnActionExecuted(actionExecutedContext);
            ApiResultModel result = new ApiResultModel();
            // 取得由 API 返回的狀態程式碼
            result.StatusCode = actionExecutedContext.ActionContext.Response.StatusCode;
            // 取得由 API 返回的資料
            result.Data = actionExecutedContext.ActionContext.Response.Content.ReadAsAsync<object>().Result;

            //請求是否成功
            result.IsSuccess = actionExecutedContext.ActionContext.Response.IsSuccessStatusCode;
            //結果轉為自定義訊息格式
            HttpResponseMessage httpResponseMessage = JsonHelper.toJson(result);
            // 重新封裝回傳格式
 actionExecutedContext.Response = httpResponseMessage;           
        }
    }
上面的JsonHelper.toJson()是事先寫好的程式碼如下:建立類JsonHelper

public static HttpResponseMessage toJson(Object obj)
        {
            String str;
            if (obj is String || obj is Char)//如果是字串或字元直接返回
            {
                str = obj.ToString();
            }
            else//否則序列為json字串
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                str = serializer.Serialize(obj);
            }
            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
            return result;
        }
建完之後在WebApiConfig下注冊:

config.Filters.Add(new ApiResultAttribute());//重新包裝結果
完成以上步驟即可使用。

補充:

特殊情況不需要封裝返回結果,解決方法:

1建立一個自定義屬性

假設自定義類名為NoPackageResult繼承Attribute


public class NoPackageResult : Attribute
    {
        
    }
2,修改上面的ApiResultAttribute類裡的OnActionExecuted方法

在方法里加一個判斷是否有屬性有的情況下就不做封裝的步驟

var noPackage = actionExecutedContext.ActionContext.ActionDescriptor.GetCustomAttributes<NoPackageResult>();
            if (!noPackage.Any())
            {
                 //執行封裝
            }         
3在不需要封裝的介面上新增屬性NoPackageResult如下:

ApiResultAttribute類完整程式碼:
public class ApiResultAttribute : System.Web.Http.Filters.ActionFilterAttribute
    {
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {            base.OnActionExecuted(actionExecutedContext);
            // 不包裹返回值
            var noPackage = actionExecutedContext.ActionContext.ActionDescriptor.GetCustomAttributes<NoPackageResult>();
            if (!noPackage.Any())
            {
                ApiResultModel result = new ApiResultModel();
                // 取得由 API 返回的狀態程式碼
                result.code = actionExecutedContext.ActionContext.Response.StatusCode;
                var a = actionExecutedContext.ActionContext.Response.Content.ReadAsAsync<object>();
                if (!a.IsFaulted)
                {
                    // 取得由 API 返回的資料
                    result.result = actionExecutedContext.ActionContext.Response.Content.ReadAsAsync<object>().Result;
                }
                //請求是否成功
                result.success = actionExecutedContext.ActionContext.Response.IsSuccessStatusCode;
                //結果轉為自定義訊息格式
                HttpResponseMessage httpResponseMessage = JsonHelper.toJson(result);

                // 重新封裝回傳格式                actionExecutedContext.Response = httpResponseMessage;
            }
        }
    }

 轉自: https://www.cnblogs.com/wuyubing/p/5307940.html