Adding User to SharePoint Group through a custom ASP.NET web service.

I had a requirement to create a web service which would be used to add user to a SharePoint group. The code for it

[WebMethod]
public  string AddSharePointUser(string username,string password, string email){
string statusInfo = “”;
try
{
s
tring SharePointUrl = ConfigurationManager.AppSettings[“SharePointUrl”].ToString();
string SharePointGroup = ConfigurationManager.AppSettings[“SharePointGroup”].ToString();

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite oSiteCollection = new
SPSite(SharePointUrl))
{
oSiteCollection.AllowUnsafeUpdates = true;
using (SPWeb oWebsite = oSiteCollection.OpenWeb())
{
oWebsite.AllowUnsafeUpdates = true;
SPUser spUser = oWebsite.EnsureUser(username);

SPGroup spGroup = oWebsite.SiteGroups[SharePointGroup];

spGroup.AddUser(spUser);
oWebsite.AllowUnsafeUpdates = false;

}

oSiteCollection.AllowUnsafeUpdates = false;

}});

statusInfo = “User Created Successfully”;

}
else
{
statusInfo = “User Already Exists”;

}}
catch (Exception ex)
{
statusInfo = ex.Message;

}
return statusInfo;

}

To run the web service successfully, we need to set the identity of application pool of the web service to SharePoint Administrator account.

Hope it helps.


Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

Share your thoughts

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s