在SharePoint中,根据登录用户加载不同的母版(Master Page)

在我们基于SharePoint 2007/2010进行扩展和自定义开发的过程中,我们可能会遇到这样的需求:根据当前登录的用户,为该用户加载起个性化的母版页。下面就来介绍实现这一需求的过程。

1. 使用 UserControl

刚得到这一需求的时候,首先想到的是创建一个UserControl,这UserControl里进行母版页的切换。经过测试,这是行不通的,尽管我们可以在这里面实现对页面样式的修改,但我们不能切换母版页了。这是因为,一旦ASP.NET页面生命周期过了OnInit后,母版页(Master Page)就被锁住并且不能更改了。

2. 使用HttpModule

这是我们实现母版页切换最常用的方式。我们可以在ASP.NET页面生命周期的PreInit方法里注册一个HttpModule的事件处理程序,在这里我们可以实现对母版页的切换,因为HttpModule可以拦截页面初始化时的事件。

在下面的实例代码中,我在Init方法里首先为PreRequestHandlerExecute事件注册一个处理程序。在PreRequestHandlerExecute 事件处理程序应用的方法里面,HttpModule类判断来自ASP.NET页面的请求是不是基于HttpHandler对象的请求。只有派生自Page的请求,HttpModule才会从PreInit事件里注册一个事件处理程序。

下面的代码是为登录的用户切换母版页。

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using Microsoft.SharePoint;

namespace SwitchMasterPage
{
    
public class CustomHttpModule : IHttpModule
    {
        
public void Dispose()
        {
        }

        
public void Init(HttpApplication context)
        {
            context.PreRequestHandlerExecute 
+= new EventHandler(context_PreRequestHandlerExecute);
        }

        
void context_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            Page page 
= HttpContext.Current.CurrentHandler as Page;
            
if (page != null)
            {
                
//为PreInit事件注册处理程序
                page.PreInit += new EventHandler(page_PreInit);
            }
        }

        
void page_PreInit(object sender, EventArgs e)
        {
            Page page 
= sender as Page;
            
if (page != null)
            {
                SPSite site 
= SPContext.Current.Site;
                
using (SPWeb web = site.OpenWeb())
                {
                    
if (web.CurrentUser != null)
                    {
                        SPGroupCollection userGroups 
= web.CurrentUser.Groups;//获取当前用户所在的sharepoint组集合
                        foreach (SPGroup group in userGroups)
                        {
                            group.Name.Contains(
"sharepoint组名称");
                            
//为该用户更换母版页
                            page.MasterPageFile = "~/catalogs/masterpage/mycustom.master";
                        }
                    }
                }
            }
        }
    }
}

值得注意的是,HttpModule不能部署在SharePoint服务器场里,它只能被部署到Web应用的级别。

现在,给该类库强命名并编译,然后把它copyGAC中。

接下来,我们要在SharePoint站点的web.config文件里注册该类,在<httpModules>节点下添加如下的代码:

View Code
<add name="CustomHttpModule" type="SwitchMasterPage.CustomHttpModule, SwitchMasterPage, Version=1.0.0.0, Culture=neutral, PublicKeyToken=7ebdb1031dfc1e406"/>
原文地址:https://www.cnblogs.com/Jayan/p/2003905.html