标签:
先创建要返回的结果类型:
/// <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());//重新包装结果
完成以上步骤即可使用。
标签:
原文地址:http://www.cnblogs.com/wuyubing/p/5307940.html