1、在App_Start文件夹添加类LoginInterceptor ,代码如下:
using Jayrock.Json.Conversion;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;
using System.Web.Routing;
public class LoginInterceptor : ActionFilterAttribute
{
#region 属性
/// <summary>
/// 记录是否登陆、已经验证
/// </summary>
public bool IsLogin { get; set; }
#endregion
//[LoginInterceptor] 在控制器类上加这个标注,标注后说明这个控制器里面都受到该拦截器限制
//[LoginInterceptor(IsLogin = true)] 在具体的方法上加这个标注,可以跳过token的验证
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// 获取当前请求的控制器和操作方法
string controllerName = filterContext.RouteData.Values["controller"].ToString();
string actionName = filterContext.RouteData.Values["action"].ToString();
// 如果当前请求的是登录操作,则不进行重定向
if (controllerName == "User" && actionName == "login")
{
base.OnActionExecuting(filterContext);
return;
}
if (!IsLogin)
{
//验证token
string token = "";
if (filterContext.HttpContext.Request.Form.AllKeys.Contains("token"))
{
token = filterContext.HttpContext.Request.Form["token"].ToString().Trim();
}
if (filterContext.HttpContext.Request.Params.AllKeys.Contains("token"))
{
token = filterContext.HttpContext.Request.Params["token"].ToString().Trim();
}
//filterContext.HttpContext.Response.Write("<script>alert('请先登录!');window.location.href='/Home/login';</script>");
//filterContext.Result =new EmptyResult();
var obj = new { succeed = false, data = "未登录或被其他人登录了,请重新登录", reload = "1" };
if (!string.IsNullOrEmpty(token))
{
T_AppToken_BLL bllToken = new T_AppToken_BLL();
if (!bllToken.isLogin(token, 1))
{
//形成日志....?
//token验证未通过
filterContext.Result = new System.Web.Mvc.JsonResult()
{
Data = obj,
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
ContentType = "json"
};
return;
}
}
else
{
//token值为空
filterContext.Result = new System.Web.Mvc.JsonResult()
{
Data = obj,
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
ContentType = "json"
};
return;
}
}
base.OnActionExecuting(filterContext);
}
}
2、[LoginInterceptor]
在控制器类上加这个标注,标注后说明这个控制器里面都受到该拦截器限制
3、 [LoginInterceptor(IsLogin = true)]
在具体的方法上加这个标注,在拦截器方法里可以跳过token的验证