码迷,mamicode.com
首页 > Windows程序 > 详细

WebApi(二)-重新封装返回结果

时间:2016-03-22 19:26:46      阅读:2248      评论:0      收藏:0      [点我收藏+]

标签:

先创建要返回的结果类型:

/// <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());//重新包装结果

完成以上步骤即可使用。

WebApi(二)-重新封装返回结果

标签:

原文地址:http://www.cnblogs.com/wuyubing/p/5307940.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!