CurrentUser 在 SharePoint 2010 应用程序页上为空

本文关键字:应用程序 SharePoint 2010 CurrentUser | 更新日期: 2023-09-27 18:31:42

我有应用程序页面,托管在 SharePoint 服务器上(例如 http://myportal/mysite/_layouts/application/default.aspx),其中包含如下代码:

protected void Page_PreLoad(object sender, EventArgs e)
{           
    var userEmail = SPContext.Current.Web.CurrentUser.Email;
}

如果用户在浏览器启动后尝试直接通过 URL 获取此页面,则会出现异常,因为 CurrentUser 为空。但是,如果用户首先导航到网站 (http://myportal/mysite),然后导航到应用程序页面,则 CurrentUser 不为空。那么,如果 CurrentUser 对象未在 SPContext 中初始化,我该如何获取它?

CurrentUser 在 SharePoint 2010 应用程序页上为空

从 RunWithElevatedPrivileges 代码中的提升的 SPWeb 获取当前用户。试试这段代码。

SPWeb site = SPContext.Current.Web;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite ElevatedsiteColl = new SPSite(site.Url))
   {
       using (SPWeb ElevatedSite = ElevatedsiteColl.OpenWeb())
       {
            SPUser currUser = site.CurrentUser; //not the ElevatedSite.CurrentUser
       }
   }
});

嗯...迟到总比不到好。 我今天遇到了同样的问题。 前面的评论没有解决原始海报表达的问题。 当您发布时出现问题。_Layouts文件夹中的 ASPX 页,然后在使用窗体或声明身份验证时,将该自定义页设置为会话中的首次点击(以前不记住登录名)。 默认情况下不会触发 SharePoint 身份验证(即使您从 LayoutsPageBase 类继承也是如此)。 如果导航到其他某个 SharePoint 页面(如 _Layouts/15/Settings.aspx),然后返回,则会填写当前用户。 我不得不使用Reflector来更好地了解正在发生的事情,以及如何解决它。 简短的回答是,一旦你意识到 CurrentUser == null,你需要添加这行代码:

Microsoft.SharePoint.Utilities.SPUtility.HandleAccessDenied(new UnauthorizedAccessException());

就我而言,此代码生成对我用于登录的浏览器的质询/响应,紧跟在这一行代码之后,CurrentUser 对象被正确填写。 这是我的整个函数最终的样子:

public static bool isAdminAuthorized()
{
    Microsoft.SharePoint.SPContext oContext ;
    Microsoft.SharePoint.SPWeb oWeb ;
    Microsoft.SharePoint.SPUser oUser ;
    try
    {
        oContext = Microsoft.SharePoint.SPContext.Current;
    }
    catch { throw new Exception("Can't obtain Sharepoint Context!"); }
    try
    {
        oWeb = oContext.Web;
    }
    catch { throw new Exception("Can't obtain Sharepoint web!"); }
    try
    {
        oUser = oWeb.CurrentUser;
    }
    catch { throw new Exception("Can't obtain Sharepoint current user!"); }
    if (oUser == null)
    {
        Microsoft.SharePoint.Utilities.SPUtility.HandleAccessDenied(new UnauthorizedAccessException());
        oUser = oWeb.CurrentUser;
    }
    foreach (Microsoft.SharePoint.SPGroup oGroup in oUser.Groups)
    {
        if (oGroup.Name.ToUpper().Contains("OWNER"))
        {
            return true;
        }
    }
    return false;
}