I am having such a bad time trying to figure this out. I'm trying to add a user to a group by posting to:
_api/web/sitegroups(8)/users
The posted data looks like this:
{ '__metadata': { 'type': 'SP.User' }, 'LoginName' : 'i:0#.w|domain\\user' }
I get Bad Request 400 and I have no idea what is wrong.
public void AddUserToGroup()
{
string requestPath = "/_api/web/sitegroups(8)/users";
string userPostBody = "{ '__metadata': { 'type': 'SP.User' }, 'LoginName':'i:0#.w|domain\\user' }";
ExecuteAuthorizedPostRequest(requestPath, userPostBody);
}
private HttpWebResponse ExecuteAuthorizedPostRequest(string requestPath, string postBody)
{
string formDigestValue = GetFormDigestValue();
HttpWebRequest request = PreparePostRequest(requestPath, formDigestValue, postBody);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
return response;
}
private HttpWebRequest PreparePostRequest(string requestPath, string formDigestValue, string postBody)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(sharepointUrl.ToString() + requestPath);
request.Method = "POST";
request.ContentType = "application/json;odata=verbose";
request.Accept = "application/json;odata=verbose";
request.Headers.Add("X-RequestDigest", formDigestValue);
request.UseDefaultCredentials = true;
request.ContentLength = postBody.Length;
byte[] postData = Encoding.ASCII.GetBytes(postBody);
Stream requestStream = request.GetRequestStream();
requestStream.Write(postData, 0, postData.Length);
requestStream.Close();
return request;
}