当前位置: 移动技术网 > IT编程>开发语言>.net > 使用ActionFilterAttribute实现MVC后台授权

使用ActionFilterAttribute实现MVC后台授权

2018年11月12日  | 移动技术网IT编程  | 我要评论

团广网,巴洛克的火焰球,纽贝斯特官网

授权就是我们在用户未登录的情况下不允许访问一些页面,只有登录后才能进行访问一些页面。

在mvc中我们可以使用actionfilterattribute来进行授权验证来阻止一些未经授权的直接访问的页面。

首先再我们的项目中根目录中创建一个文件夹命名为filter,在该文件夹内创建一个普通的类,注意:类名必须以 "attribute" 结尾。

下图代码为授权验证类:

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.web;
 5 using system.web.mvc;
 6 
 7 namespace mvc_crud.filters
 8 {
 9     public class myauthorizefilterattribute : actionfilterattribute//必须继承于actionfilterattribute
10     {
11         public override void onactionexecuted(actionexecutedcontext filtercontext)//重写onactionexecuted,
12         {
13             base.onactionexecuted(filtercontext);
14             httpcontextbase http = filtercontext.httpcontext;
15             if (http.request.cookies["adminname"]==null)//判断是否有cookise(用户登录存入的cookise)
16             {
17                 http.response.redirect("http://www.lhsxpumps.com/_localhost:1299/home/login");//要跳转的页面(一般都是跳转至登录页)
18             }
19         }
20     }
21 }

写好授权后,我们要在需要授权的控制器中加上我们的特性,比如我要在index上验证未登录用户不可访问,可以在它的action上方加上[myauthorizefilter]

注意我们要在using 引用我们的文件,否则会找不到。

 

 如果整个控制器的action中需要授权验证,那么可以在控制器类上方加上[myauthorizefilter]。

这样可以达到当我们运行一个授权的页面在未登录的情况下自动跳转到登录页面。

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网