Sharepoint 2013: EnsureUser via REST API

前端 未结 2 1670
悲&欢浪女
悲&欢浪女 2021-01-03 16:44

I\'m trying to ensure some users automatically via REST API. My REST call:

$.ajax({
url: \"blablabla/_api/web/ensureuser\",
type: \"POST\",
data: \"{ \'logon         


        
相关标签:
2条回答
  • 2021-01-03 17:06

    This error occurs since ContentType needs to be specified explicitly since it's a JSON request:

    contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')

    When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8"

    Example

    function ensureUser(webUrl,loginName)
    {
       var payload = { 'logonName': loginName }; 
       return $.ajax({
          url: webUrl + "/_api/web/ensureuser",
          type: "POST",
          contentType: "application/json;odata=verbose",
          data: JSON.stringify(payload),
          headers: {
             "X-RequestDigest": $("#__REQUESTDIGEST").val(),
             "accept": "application/json;odata=verbose"
          }
       });  
    }
    
    
    var loginName = 'i:0#.f|membership|jdoe@contoso.onmicrosoft.com'
    ensureUser(_spPageContextInfo.webAbsoluteUrl,loginName)
    .done(function(data)
    {
        console.log('User has been added');
    })
    .fail(function(error){
        console.log('An error occured while adding user');
    });
    
    0 讨论(0)
  • 2021-01-03 17:21

    ALTERNATIVE SOLUTION:

    You could also perform a REST query in the following way:

            $.ajax({
            url: "http://[website]/_api/web/ensureuser('"+user_name+"')",
            type: "POST",
            headers: {             
                'accept': 'application/json;odata=verbose;charset=utf-8',
                'Content-Type': 'application/json;odata=verbose;charset=utf-8',
                'X-RequestDigest': $("#__REQUESTDIGEST").val()                    
            },
            success: function(response_data){ [your custom success action]
            },
            error: function(response_data){[your custom fail action]}
          });
    

    var user_name will contain target AD username.

    NOTE:

    • When using the ensureUser method against an AD user, just use its username. So, user_name would be something like this: "username". No need to add "domain\" before neither any other kind of prefix/suffix. Just the username

    • ContentType & accept headers MUST be application/json;odata=verbose;charset=utf-8

    0 讨论(0)
提交回复
热议问题