zoukankan      html  css  js  c++  java
  • ASP.NET MVC 用户权限-1

    MVC框架的开发网站的利器,MVC框架也开始越来越流行了。对于.NET ,微软也发布了MVC框架,做网站通常要涉及到用户的权限管理,对于.NET MVC 框架的用户权限管理又应该怎样设置呢?下面通过示例讲解一下怎样实现.NET MVC 用户权限管理。

    查看微软MSDN库我们知道,ASP.NET MVC权限控制都是通过实现AuthorizeAttribute类的OnAuthorization方法。因此我们需要将一个类来继承AuthorizeAttribute类,并实现OnAuthorization方法。如下面的代码我们建一个CustomAuthorizeAttribute类

    [cce_cs]
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    
    ///
    /// Summary description for CustomAuthorizeAttribute
    ///
    
    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            bool isAuthenticated=HttpContext.Current.Session["User"]==null?false:true;
            if (!isAuthenticated)
            {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "account", action = "login", returnUrl = filterContext.HttpContext.Request.Url, returnMessage = "您无权查看." }));
                return;
            }
            base.OnAuthorization(filterContext);
        }
    }
    [/cce_cs]

    上面的代码假设用户登录的标识是存储Session中,key为USer,这样通过判断是否有这个标识作为是否登录的判断,当然这里的用户登录标识只是示例,你完全可以根据自己的方法实现isAuthenticated的登录判断。如果没有登录,上面的代码会重定向到登录页面。

    因此我们现在有了CustomAuthorizeAttribute标签,只需要给我们的Action方法打上[CustomAuthorizeAttribute] 标签就可以了,如下面的代码:

    [cce_cs]
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace SampleMVCWebsite.Controllers
    {
        public class HomeController : Controller
        {
            //
            // GET: /Home/
            [CustomAuthorize]
            public ActionResult Index()
            {
                return View();
            }
        }
    }
    [/cce_cs]

    这样上面的代码就会有这样的效果:当访问 HomeController 的 Index 方法的时候就会首先执行 CustomAuthorizeAttribute 类中的
    OnAuthorization判断是否登录,如果没有就跳到登录页面。

    像上面这种方式是比较粗粒度的解决方案,由于是已经将定义好权限的固定代码带对应的Action上,所以无法实现用户自定义权限控制。下一次教程讲解.NET MVC基于角色的权限控制系统。

  • 相关阅读:
    在线学习VIM
    对三叉搜索树的理解
    Suffix Tree
    Skip list
    中文分词算法
    土豆的seo
    Gentle.NET文档(链接)
    a标签的link、visited、hover、active的顺序
    html dl dt dd标签元素语法结构与使用
    WEBZIP为什么打不开网页
  • 原文地址:https://www.cnblogs.com/wfy680/p/12326013.html
Copyright © 2011-2022 走看看