ASP.NET MVC 使用者權限管理執行個體代碼

來源:互聯網
上載者:User

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基於角色的許可權控制系統

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.