SharePoint Check user has permission
By Jatin Prajapati
In this FAQ we will see how to check that a logged in user has access to the site or sub site of the current site using C#.
Many times while working in SharePoint we need to check using code that the current
logged in user has access to a particular site or sub site, so that we can avoid
the Access Denied error page. So, to do this using C# please refer the below
code.
using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Collections.Generic;
namespace WebParts.FacetedNavigationWebPart
{
[ToolboxItem(false)]
public partial class FacetedNavigationWebPart : System.Web.UI.WebControls.WebParts.WebPart
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
InitializeControl();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SPWeb web = SPContext.Current;
string userLoginName = web.CurrentUser.LoginName;
if (IsUserHasAccess(web, userLoginName))
{
lbl.Text = "User has access to " + web.Title;
}
else {
lbl.Text = "User has no access to " + web.Title;
}
}
}
private bool IsUserHasAccess(SPWeb web, string userLoginName)
{
bool hasAccess = false;
try
{
web.Site.CatchAccessDeniedException = false;
hasAccess = web.DoesUserHavePermissions(userLoginName, SPBasePermissions.EmptyMask);
}
catch
{
hasAccess = false;
}
return hasAccess;
}
}
}
SharePoint Check user has permission (2406 Views)