【asp.net core】ASP.NET MVC 用户权限管理实例代码

更新时间:2019-08-06    来源:ASP.NET MVC    手机版     字体:

【www.bbyears.com--ASP.NET MVC】

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

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

 代码如下

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);
    }
}


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

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

 代码如下

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();
        }
    }
}


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

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

本文来源:http://www.bbyears.com/asp/60410.html