一般在执行MVC项目时,常常会出现在地址栏中,直接输入控制器/操作方法实现跳过登录直接进去系统。但在实际工作或使用系统时,是不允许用户跳过登录界面直接进入后台系统的。
这时,我们可以通过两种办法进行杜绝。过滤器和身份票据
1、身份票据:
1>在Web config中的<System.web>节点下添加:
<authentication mode="Forms">
<froms loginUrl="初始/打回界面url" timeout="2880" />
</authentication>
2>在登陆处保存session的地方创建身份票据:
FormsAuthentication.SetAuthCookie("放身份票据,可以是用户名",false);
//false表示是否为永久保存
3>在控制器中登录成功跳转的操作方法上加上一条注解:[Authorize]
2、过滤器
1>创建一个Filters文件夹,并创建类(类名最好为登录界面的操作方法名:xxLoginFilters)
2>引入命名空间:using System.Web.MVC;
3>类继承:ActionFilterAttribute
4>重写方法:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//1、不弹提示
filterContext.Result = new RedirectResult("初始页面/打回页面");
//2、弹提示
if (HttpContext.Current.Session[""]==null)
{
filterContext.Result = new ContentResult() { Content = "<script>alter('请先登录')</script>" };
}
}
5>在控制器引入文件夹空间,在需要过滤的操作方法上加入注解:[Feilter文件夹中对应的类名]