码迷,mamicode.com
首页 > Web开发 > 详细

ASP.NET MVC 用户权限-1

时间:2020-02-18 14:54:30      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:auth   cat   ica   ESS   nbsp   ssi   attr   cWeb   ace   

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基于角色的权限控制系统。

ASP.NET MVC 用户权限-1

标签:auth   cat   ica   ESS   nbsp   ssi   attr   cWeb   ace   

原文地址:https://www.cnblogs.com/wfy680/p/12326013.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!