Dynamics 365 获取用户角色名称再也不用额外查询一次了。

我是微软Dynamics 365 & Power Platform方面的工程师罗勇,也是2015年7月到2018年6月连续三年Dynamics CRM/Business Solutions方面的微软最有价值专家(Microsoft MVP),欢迎关注我的微信公众号 MSFTDynamics365erLuoYong ,回复399或者20200407可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me!

V9以前的版本获取当前用户拥有的角色名称,首先要通过 Xrm.Page.context.getUserRoles() 这个API来获取用户拥有角色的ID组成的数组,然后调用一次Web API来转换成名称。

V9开始,Xrm.Page不再推荐使用,而是推荐使用 Xrm.Utility,所以写代码要注意用新方法。

Xrm.Utility.getGlobalContext().userSettings.securityRoles 和原来的 Xrm.Page.context.getUserRoles() 返回是一样的,也是返回用户拥有角色的ID组成的数组,但是这个也不再推荐使用,官方文档是 getGlobalContext.userSettings (Client API reference) ,描述如下: 

securityRoles
Returns an array of strings that represent the GUID values of each of the security role or teams that the user is associated with.

Deprecated; use userSettings.roles instead to view the display names of security roles or teams along with the ID.

Syntax
userSettings.securityRoles

Return Value
Type: Array

Description: GUID values of each of the security role. For example:

["0d3dd20a-17a6-e711-a94e-000d3a1a7a9b", "ff42d20a-17a6-e711-a94e-000d3a1a7a9b"]

 

推荐使用的是Xrm.Utility.getGlobalContext().userSettings.roles,官方描述如下:

roles
Returns a collection of lookup objects containing the GUID and display name of each of the security role or teams that the user is associated with.

Syntax
userSettings.roles

Return Value
Type: Array of objects

Description: Object containing id and name of each of the security role or teams that the user is associated with.

 

可以得知,返回的集合中的每个对象包括了角色的GUID和角色的名称,所以再也不用额外查询一次了,我这里搞个简单例子,根据角色列表来判断用户是否有该角色:

        CheckUserHasRoles: function (checkRoles) {
            var returnVal = false;
            var currentRoles = Xrm.Utility.getGlobalContext().userSettings.roles;
            checkRoles.split(',').forEach(function (checkRole) {
                currentRoles.forEach(function (currentRole) {
                    if (checkRole.toLowerCase() === currentRole.name.toLowerCase()) {
                        returnVal = true;
                    }
                });
            });
            return returnVal;
        }

 

也可以考虑如下的写法,可以使用break,上面的forEach写法不能使用break语句。

            var isAdmin = false;
            var currentRoles = Xrm.Utility.getGlobalContext().userSettings.roles;
            for (let i = 0; i < currentRoles.getLength(); i++) {
                if (currentRoles.get(i).name === "System Administrator") {
                    isAdmin = true;
                    break;
                }
            }

 

posted @ 2020-04-07 18:30  微软MVP(15-18)罗勇  阅读(679)  评论(0编辑  收藏  举报