ASP.NET Identity “角色-許可權”管理 9

來源:互聯網
上載者:User

標籤:

1.1.       對象映射

參考1:https://github.com/AutoMapper/AutoMapper

參考2:AutoMapper的配置方法

參考3:使用AutoMapper實現Dto和Model的自由轉換(上)

 

為適應View的變化,將資料封裝到ViewModel,從而保持領域模型的純淨穩定,這裡使用AutoMapper處理Model與ViewModel之間映射。

1.1.1.      映射類Profile

繼承自Profile,每個映射類中就是一套對象間映射規則,根據實際需要可設定多套規則。

[Description("AutoMapper配置")]

public class AutoMapperProfile : AutoMapper.Profile

{

    protected override void Configure()

    {

        CreateMap<ApplicationPermission, PermissionViewModel>();

        CreateMap<PermissionViewModel, ApplicationPermission>();

        CreateMap<ApplicationRole, RoleViewModel>();

        CreateMap<RoleViewModel, ApplicationRole>()

            .ForMember(

                        dest => dest.Id,

                        sour =>

                        {

                            sour.MapFrom(s => s.Id ?? System.Guid.NewGuid().ToString());

                        });

           

        CreateMap<ApplicationUser, EditUserViewModel>();

        CreateMap<EditUserViewModel, ApplicationUser>();

        CreateMap<RegisterViewModel, ApplicationUser>();

    }

}

 

1.1.2.      配置類

載入映射規則,提供靜態方法供外部調用。

[Description("AutoMapper匹配")]

public class AutoMapperConfig

{

    public static void Configure()

    {

        AutoMapper.Mapper.Initialize(cfg =>

        {

            cfg.AddProfile<AutoMapperProfile>();

        });

    }

}

 

1.1.3.      修改全域類

修改Global.asax,MVC啟動時載入AutoMapper配置。

public class MvcApplication : System.Web.HttpApplication

{

    protected void Application_Start()

    {

        AreaRegistration.RegisterAllAreas();

        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

        RouteConfig.RegisterRoutes(RouteTable.Routes);

        BundleConfig.RegisterBundles(BundleTable.Bundles);

        //AutoMapper配置

        AutoMapperConfig.Configure();

    }

}

 

1.2.       分頁

參考1:MvcPager概述

參考2:無廢話MVC入門教程八[MvcPager分頁控制項的使用]

 

分頁是經常用到的功能,這裡採用國內開原始檔控制MvcPager提供的Ajax分頁,該控制項可通過NuGet安裝。

1.2.1.      Controller

添加引用Webdiyer.WebControls.Mvc,增加頁索引參數Index,返回資料調用ToPagedList(index,pagesize)方法。

using Webdiyer.WebControls.Mvc;

 

    // GET: RolesAdmin

    [Description("角色列表")]

    public ActionResult Index(int index = 1)

    {

        var roles = _roleManager.Roles;

        var views = new List<RoleViewModel>();

        foreach (var role in roles)

        {

            var view = Mapper.Map<RoleViewModel>(role);

            views.Add(view);

        }

        return View(views.ToPagedList(index, 10));//顯示角色清單

    }

 

1.2.2.      View

同樣先添加引用,model類型變更為IPagedList,建立id名為views的div,添加分頁參數,增加指令碼引用。

注意:PageIndexParameterName值應與Action的頁索引參數一致,UpdateTargetId應於div的id一致。

@using Webdiyer.WebControls.Mvc

 

@model IPagedList<AspNetIdentity2Permission.Mvc.Models.RoleViewModel>

 

省略頁面代碼…

<div id="views">

 

<table class="table table-hover table-striped">

省略table代碼。。。

    </table>

 

    @Ajax.Pager(Model, new PagerOptions { PageIndexParameterName = "index" }, new MvcAjaxOptions { UpdateTargetId = "views", EnablePartialLoading = true })

</div>

@section Scripts{@{Html.RegisterMvcPagerScriptResource();}}

 

1.2.3.      運行效果

    整體效果。

 

    分頁效果。

 

 

1.3.       緩衝1.3.1.      Application

因反射效率不高,而程式集一旦編譯,內部的許可權資訊是固定不變的,所以將這些資訊緩衝在Application可提高效率。

程式集許可權資訊緩衝。

/// <summary>

/// 緩衝key

/// </summary>

const string _permissionKey = "PermissionsOfAssembly";

/// <summary>

/// 程式集中許可權集合

/// </summary>

protected IEnumerable<ApplicationPermission> _permissionsOfAssembly

{

    get

    {

        //從緩衝讀取許可權資訊

        var permissions = HttpContext.Application.Get(_permissionKey)

                            as IEnumerable<ApplicationPermission>;

        if (permissions == null)

        {

            //取程式集中全部許可權

            permissions = ActionPermissionService.GetAllActionByAssembly();

            //添加到緩衝

            HttpContext.Application.Add(_permissionKey, permissions);

        }

        return permissions;

    }

}

 

1.3.2.      Session

同理,驗證需要頻繁訪問使用者權限,緩衝使用者-許可權亦能提高效率,所以該部分資料儲存在Session中。

/// <summary>

/// 取目前使用者的許可權列表

/// </summary>

/// <param name="context"></param>

/// <returns></returns>

private IEnumerable<ApplicationPermission> GetUserPermissions(HttpContextBase context)

{

    //取登入名稱

    var username = context.User.Identity.Name;

    //構建緩衝key

    var key = string.Format("UserPermissions_{0}", username);

    //從緩衝中取許可權

    var permissions = HttpContext.Current.Session[key]

                        as IEnumerable<ApplicationPermission>;

    //若沒有,則從db中取並寫入緩衝

    if (permissions == null)

    {

        //取rolemanager

        var roleManager = context.GetOwinContext().Get<ApplicationRoleManager>();

        //取使用者權限集合

        permissions = roleManager.GetUserPermissions(username);

        //寫入緩衝

        context.Session.Add(key, permissions);

    }

    return permissions;

}

 

1.3.3.      修改登出邏輯

為避免同一台機器不同使用者登入時出現許可權混亂,使用者登出時要清除Session緩衝,修改AccountController.cs中LogOff,登出時清除所有緩衝。

[HttpPost]

[ValidateAntiForgeryToken]

public ActionResult LogOff()

{

    AuthenticationManager.SignOut();

    //移除緩衝

    base.HttpContext.Session.RemoveAll();

    return RedirectToAction("Index", "Home");

}

ASP.NET Identity “角色-許可權”管理 9

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.