Asp.net MVC Filter 过滤器

简单的认证设置:

1.在Web.config配置文件中增加

<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880">
<credentials passwordFormat="Clear">
<user name="user" password="123"/>
<user name="admin" password="tt123"/>
</credentials>
</forms>
</authentication>

说明:使用Forms认证,对于未通过的认证直接重定向到Account控制器的Login方法中。

2.应用单元 using System.Security

在需要验证登录才能授权使用的控制器上加上[Authorize] 启用授权验证功能

当访问该控制器方法时,会自动重定向到指定的Url进行验证。

3.系统验证

调用FormsAuthentication.Authenticate(username,password);进行验证,该方法会自动匹配配置文件中Forms的credentials 节点中的user,当然自己也可以通过自定义方法来通过数据库或配置文件来验证。

验证成功后可以通过 FormsAuthentication.SetAuthCookies(username,false)来保存用户名为cookies变量,这样下次登录就会缓存。

 

MVC支持5种不同的过滤器

1.认证过滤器  IAuthenticationFilter                   最先运行,在任何其他过滤器方法之前,但授权过滤器之后可以再次运行

2.授权过滤器 IAuthenticationFilter   AuthorizeAttribute  在认证过后,其他过滤器活动作方法之前,第二个运行

3.动作过滤器  IActionFilter    ActionFilterAttribute   在动作方法之前及之后运行

4.结果过滤器 IResultFilter  ActionFilterAttribute  在动作结果被执行之前和之后运行

5.异常过滤器 IExceptionFilter HandleErrorAttribute 仅在另一个过滤器、动作方法或动作结果抛出异常时运行。

 AuthorizeAttribute属性

Users string  一个逗号分隔的用户名列表,允许这些用户访问该动作方法

Roles string  一个逗号分隔的角色列表,为了访问该动作方法,用户必须至少是这些角色之一。

 

posted @ 2020-10-07 14:11  丹心石  阅读(106)  评论(0编辑  收藏  举报