Net WebApi 基本过滤器以及统一返回结果集处理
可以根据自己的业务区更改
using HomeMediaFileManageSystemBusiness.HomeMediaBusiness.BaseApi;
using HomeMediaFileManageSystemUtilts.Log;
using HomeMediaFileManageSystemUtilts.Security;
using HomeMediaFileManageSystemUtilts.Session;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using Newtonsoft.Json;
namespace HomeMediaFileManageSystemApi.Controllers
{
/***
*
* 系统过滤器 过滤请求进入方法之前和请求进入方法之后执行这些过滤信息
**/
public class BaseApiFilter: System.Web.Http.Filters.ActionFilterAttribute
{
#region 验证 是否是 post 请求 以及登录权限
/// <summary>
/// 验证 是否是 post 请求 以及 登录权限
/// </summary>
/// <param name="actionContext"></param>
public override void OnActionExecuting(HttpActionContext actionContext)
{
//如果有匿名特性 直接返回 不验证
var isAllow= actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();
if (isAllow) {
return;
}
//检查Action方法是否是post请求
var isHttpPost = actionContext.ActionDescriptor.GetCustomAttributes<HttpPostAttribute>().Any();
if (isHttpPost)
{
//获取请求中是否有Token参数
var argument=actionContext.ActionArguments.ToList();
try
{
JObject obj = JObject.Parse(argument[0].Value.ToString());
if (obj.ContainsKey("Token"))
{
//解密token
var decToken= new DESEncrypt().DesDecrypt(obj["Token"].ToString(), "HomeMedia");
var account=decToken.Split('&')[0];
var pwd = decToken.Split('&')[1];
bool isUser = new IsUserVerifyPermissions().IsUserPermission(account, pwd);
if (isUser)
{
return;
}
else {
actionContext.Response = new HttpResponseMessage() { Content = new StringContent("对不起你没有权限访问"), StatusCode = System.Net.HttpStatusCode.OK };
Log.Warn("可能有非法用户攻击");
}
}
else {
//非法访问不允许
actionContext.Response = new HttpResponseMessage() { Content=new StringContent("非法请求不允许"), StatusCode=System.Net.HttpStatusCode.OK };
}
}
catch (Exception ex)
{
actionContext.Response = new HttpResponseMessage() { Content = new StringContent("无效请求"), StatusCode = System.Net.HttpStatusCode.OK };
}
}
else {
//不是post请求
actionContext.Response = new HttpResponseMessage() { Content = new StringContent("此接口不支持GET请求"), StatusCode = System.Net.HttpStatusCode.OK };
}
}
#endregion
#region 对api方法返回结果做统一处理
/// <summary>
/// 对api方法返回结果做统一处理
/// </summary>
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
//检查Action方法是否有特性
var attributeAttr = actionExecutedContext.ActionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();
//如果存在则对结果集不进行系统自定义序列化方式
if (attributeAttr)
{
return;
}
else {
//统一处理结果集并序列化
if (actionExecutedContext.Exception == null) {
var obj=actionExecutedContext.ActionContext.Response.Content.ReadAsAsync<object>().Result;
HttpResponseMessage message = new HttpResponseMessage() {
Content=new StringContent(JsonConvert.SerializeObject(obj)),
StatusCode=System.Net.HttpStatusCode.OK,
};
}
}
}
#endregion
}
}