专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > ASP

ASP.NET MVC中利用AuthorizeAttribute实现访问身份是否合法以及Cookie过期有关问题的处理

发布时间:2010-05-20 14:01:29 文章来源:www.iduyao.cn 采编人员:星星草
ASP.NET MVC中利用AuthorizeAttribute实现访问身份是否合法以及Cookie过期问题的处理

话说来到上海已经快半年了,时光如白驹过隙,稍微不注意,时间就溜走了,倒是没有那么忙碌,闲暇之际来博客园还是比较多的,记得上次在逛博问的时候看到有同志在问MVC中Cookie过期后如何作相关处理,他在阐述那么多页面不可能都去一个个手动处理。其实MVC很牛逼的地方就是把Attribute利用的非常完美,接下来就来看下它是如何做到的吧!

第一步、我们要定义一个登录过滤标签-LoginFilterAttribute并且继承AuthorizeAttribute。来看下它内部是啥样子

 1 // Summary:
 2     //     Represents an attribute that is used to restrict access by callers to an
 3     //     action method.
 4     [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
 5     public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter
 6     {
 7         // Summary:
 8         //     Initializes a new instance of the System.Web.Mvc.AuthorizeAttribute class.
 9         public AuthorizeAttribute();
10 
11         // Summary:
12         //     Gets or sets the user roles.
13         //
14         // Returns:
15         //     The user roles.
16         public string Roles { get; set; }
17         //
18         // Summary:
19         //     Gets the unique identifier for this attribute.
20         //
21         // Returns:
22         //     The unique identifier for this attribute.
23         public override object TypeId { get; }
24         //
25         // Summary:
26         //     Gets or sets the authorized users.
27         //
28         // Returns:
29         //     The authorized users.
30         public string Users { get; set; }
31 
32         // Summary:
33         //     When overridden, provides an entry point for custom authorization checks.
34         //
35         // Parameters:
36         //   httpContext:
37         //     The HTTP context, which encapsulates all HTTP-specific information about
38         //     an individual HTTP request.
39         //
40         // Returns:
41         //     true if the user is authorized; otherwise, false.
42         //
43         // Exceptions:
44         //   System.ArgumentNullException:
45         //     The httpContext parameter is null.
46         protected virtual bool AuthorizeCore(HttpContextBase httpContext);
47         //
48         // Summary:
49         //     Processes HTTP requests that fail authorization.
50         //
51         // Parameters:
52         //   filterContext:
53         //     Encapsulates the information for using System.Web.Mvc.AuthorizeAttribute.
54         //     The filterContext object contains the controller, HTTP context, request context,
55         //     action result, and route data.
56         protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext);
57         //
58         // Summary:
59         //     Called when a process requests authorization.
60         //
61         // Parameters:
62         //   filterContext:
63         //     The filter context, which encapsulates information for using System.Web.Mvc.AuthorizeAttribute.
64         //
65         // Exceptions:
66         //   System.ArgumentNullException:
67         //     The filterContext parameter is null.
68         public virtual void OnAuthorization(AuthorizationContext filterContext);
69         //
70         // Summary:
71         //     Called when the caching module requests authorization.
72         //
73         // Parameters:
74         //   httpContext:
75         //     The HTTP context, which encapsulates all HTTP-specific information about
76         //     an individual HTTP request.
77         //
78         // Returns:
79         //     A reference to the validation status.
80         //
81         // Exceptions:
82         //   System.ArgumentNullException:
83         //     The httpContext parameter is null.
84         protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext);
85     }

这里我们要重写OnAuthorization这个方法。

接下来就看下LoginFilterAttibute这个"儿子"是怎么完成"老子"交待的任务了。直接上code

 1 public class LoginFilterAttribute:AuthorizeAttribute
 2     {
 3 
 4         private static string formsCookieName = FormsAuthentication.FormsCookieName;
 5 
 6         public override void OnAuthorization(AuthorizationContext filterContext)
 7         {
 8            HttpCookie formsCookie =
 9                 System.Web.CookieManager.GetCookie(formsCookieName);
10             if (formsCookie == null)
11             {
12                 //页面Cookie过期后返回登录页面
13                 RedirectToLoginPage(filterContext);
14                 return;
15             }
16  
17             bool autenticated = HttpContext.Current.User.Identity.IsAuthenticated;
18 
19             //一旦发现身份不合法就作相应的处理.
20             if (!autenticated )
21             {
22                 //redirect to login
23                 RedirectToLoginPage(filterContext);
24                 return;
25             }
26             //if success add login data to context
27         }
28            private static void RedirectToLoginPage(AuthorizationContext filterContext)
29         {
30             if (filterContext.HttpContext.Request.IsAjaxRequest())
31             {
32                 filterContext.Result = new JsonResult() 
33                 { 
34                     Data = new {
35                         status = "error",
36                         message = "Unauthorized_Message"
37                     },
38                     JsonRequestBehavior= JsonRequestBehavior.AllowGet
39                 };
40                 return;
41             }
42 else
43 {
44          //返回登录页面的相关处理..........
45 }
}

第二步、新建一个基类Controller-BaseController并且继承Controller。

1     [LoginFilter]//此处就是我们上面定义的LoginFilterAttribute
2     public abstract partial class BaseController : Controller
3     {
4         public BaseController(){ 
5         
6         }
7       //........其他相关处理
8     }

第三步、不是有很多页面吗?那我只要在对应的Controller去继承那个BaseController就实现了,在访问任何一个页面都会去作相应的过滤和处理。

1 Public Class LoginController:BaseController
2 {
3      Public ActionResult Index()
4     {
5       //........
6        return  View();
7     }
8 }

以上纯属个人观点,如有雷同纯属巧合!谢谢阅读,如果对您有帮助,请点关注并推荐!

友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

  • ASP怎么隐藏表单

    ASP如何隐藏表单 <%if Cookies_Toy ="" then response.write "<a href='login.asp'>登录</a> <a href='reg.asp'>注册</a>" ...

  • 为何js调用css脚本后没效果

    为什么js调用css脚本后没效果 这个是css的脚本代码: body,ul,li{margin: 0; padding: 0; border: 0;} body {background: #f5f...

  • 怎么伪造post请求,求指点。

    如何伪造post请求,求指点。。。 要查询大批(也就几万个)运单的状态,那查询网站一次最多查24个,这一个个搞会搞死人的。。 有...

  • Asp.net_简略代码设置GridView自适应列宽不变形

    Asp.net_简单代码设置GridView自适应列宽不变形 动态绑定的GridView由于列数不固定,而列又太多(博主做的这个项目有150个左右的字段...

  • ASP.NET上实现AJAX注册提醒

    ASP.NET下实现AJAX注册提醒 Ajax全称是,主要是利用JavaScript实现异步的数据传输,首先说异步,异步是当前操作进行的时候,用...

  • aspnet_regiis装配出错:0x80070005 拒绝访问

    aspnet_regiis安装出错:0x80070005 拒绝访问 点击右边红色标题查看本文完整版:aspnet_regiis安装出错:0x80070005 拒绝访问安装...

  • 关于网站边框解决方法

    关于网站边框 像hao123这样的网站上的边框是着么弄的?背景图片吗?http://www.hao123.com 另外哪个素材网站有实用的这内素材 -----...

  • ! 多表分组查询统计

    求助!! 多表分组查询统计 高手们,帮帮忙! 用户表 D_user 为 ID Username GroupID 1 张三 2 2 李四 2 3 王五 ...

  • 在Paypal交付的同时,把表单的数据提交给数据库

    在Paypal提交的同时,把表单的数据提交给数据库 本帖最后由 liuyang2708 于 2012-11-20 23:14:54 编辑 在提交这个支付...

  • 虚拟目录上JavaScript不能正常执行

    虚拟目录下JavaScript不能正常执行 各位大侠好,我在同一台服务器上用两种方式部署同一个网站。 第一种方法:在IIS下直接建一个网站...

热门推荐: