1.用户登陆验证过滤器
创建Filters文件夹,里面创建UserRoleAttribute.cs文件
1.继承System.Web.Mvc.ActionFilterAttribute(自定义过滤器)
2.首先获取当前请求的控制器名称
3.判断是否请求的是Login控制器,如果是,则允许,如果否,则判断Session是否存在
4.如果Session存在则允许访问,如果不存在跳转登陆页面
注:
这里只是做了简单的用户验证,可自行根据系统需求进行复杂的过滤验证;
SessionHelper可以从百度查找代码实现;
public class UserRoleAttribute : System.Web.Mvc.ActionFilterAttribute
{
public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
{
string controller = filterContext.RouteData.Values["controller"].ToString();//控制器名称
if (controller == "Login")
{
base.OnActionExecuting(filterContext);
return;
}
string User = MvcDemo.Common.SessionHelper.Get("User");
if (string.IsNullOrEmpty(User))
{
//这里构造了一个心得ActionResult
filterContext.Result = new System.Web.Mvc.RedirectResult("/Login/Index");
return;
}
else
{
base.OnActionExecuting(filterContext);
return;
}
}
}
附上SessionHelper.Get代码
/// <summary>
/// 读取某个Session对象值
/// </summary>
/// <param name="strSessionName">Session对象名称</param>
/// <returns>Session对象值</returns>
public static string Get(string strSessionName)
{
if (HttpContext.Current.Session[strSessionName] == null)
{
return null;
}
else
{
return HttpContext.Current.Session[strSessionName].ToString();
}
}
2.全局异常处理过滤器
当WEB应用发生异常时,都会进入该过滤器
public class SystemErrorAttribute : System.Web.Mvc.HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
base.OnException(filterContext);
//处理错误消息,将其跳转到一个页面
string controllerName = (string)filterContext.RouteData.Values["controller"];
string actionName = (string)filterContext.RouteData.Values["action"];
//使用log4net来记录
ILog log = log4net.LogManager.GetLogger("controllerName:[" + controllerName + "]actionName:[" + actionName + "]");
log.Error(filterContext.Exception.ToString());
//错误友好輸出,这里重新构造了一个ActionResult
//filterContext.Result = new System.Web.Mvc.ContentResult() { Content = "系统错误,请联系管理员" };
filterContext.ExceptionHandled = true;
}
}
3.添加过滤器
项目/App_Start/FilterConfig.cs 补充下面添加过滤器的代码
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
//全局异常处理记录
filters.Add(new HandleErrorAttribute());
//全局权限访问控制
filters.Add(new Filters.UserRoleAttribute());
//全局自定义异常处理记录
filters.Add(new Filters.SystemErrorAttribute());
}