【问题标题】:CurrentUser is null on Sharepoint 2010 application pageSharepoint 2010 应用程序页面上的 CurrentUser 为空
【发布时间】:2016-07-01 17:27:40
【问题描述】:

我有一个托管在 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 中初始化,如何获取它呢?

【问题讨论】:

    标签: c# sharepoint-2010 spcontext


    【解决方案1】:

    从 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
           }
       }
    });
    

    【讨论】:

    • 不幸的是 site.CurrentUser 为空。
    【解决方案2】:

    嗯...迟到总比没有好。我今天遇到了同样的问题。先前的评论没有解决原始发布者表达的问题。当您在 _Layouts 文件夹中发布 .ASPX 页面时,问题就出现了,然后,当使用 Forms 或 Claims auth 时,将该自定义页面设为您在会话中的第一次点击(之前没有记住登录)。默认情况下不会触发 SharePoint 身份验证(即使您从 LayoutsPageBase 类继承)。如果您导航到其他一些 SharePoint 页面(例如 _Layouts/15/Settings.aspx)然后返回,则 CurrentUser 已填写。我必须使用 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;
    }
    

    【讨论】:

      猜你喜欢
      • 2011-05-31
      • 2011-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-04
      • 2021-09-16
      • 2018-05-31
      相关资源
      最近更新 更多