2017-02-01 2 views
0

У меня возникла проблема с получением изображения профиля из аккаунта Delve. Вот пример ссылки, которая возвращает мне фотографию, когда я помещаю ее в браузер: https://orgname.sharepoint.com/_vti_bin/DelveApi.ashx/people/[email protected]&size=LПолучить фото с Delve profile of Office365 с помощью запроса REST

Теперь мне нужно получить эту фотографию из кода. Я пробовал такой способ, который работает идеально подходит для внешних изображений не Office365:

var credentials = new NetworkCredential("myemail", "password"); 
using (var handler = new HttpClientHandler { Credentials = credentials }) 
using (var client = new HttpClient(handler)) 
{ 
    var bytes = await client.GetByteArrayAsync(url); 
    return Convert.ToBase64String(bytes); 
} 

Но Быстродействие я получаю HTML-страницы с текстом, как:

<H1>We can't sign you in</H1><p>Your browser is currently set to block cookies. You need to allow cookies to use this service.</p><p>Cookies are small text files stored on your computer that tell us when you're signed in. To learn how to allow cookies, check the online help in your web browser.</p> 

Я думаю, что это связано с Office365 авторизации, но Я не знаю, как выполнить запрос REST на этот адрес со своими учетными данными ...

ответ

1

проблема решена, сначала необходимо инициализировать контекст SharePoint:

public ClientContext SetupSpContext() 
    { 
     // This builds the connection to the SP Online Server 
     var clientContext = new ClientContext(_sharePointCrmDocumentsSiteName); 
     var secureString = new SecureString(); 
     foreach (var c in _sharePointCrmDocumentsPwd.ToCharArray()) secureString.AppendChar(c); 
     { 
      clientContext.Credentials = new SharePointOnlineCredentials(_sharePointCrmDocumentsLoginName, secureString); 
     } 
     var web = clientContext.Web; 
     clientContext.Load(web); 
     clientContext.ExecuteQuery(); 
     return clientContext; 
    } 

Тогда мы можем получить фотографию из Shrepoint с помощью электронной почты пользователя:

public string DownloadProfilePictureAsBase64(string email) 
    { 
     try 
     { 
      var pictureUrl = GetPictureUrl(email); 

      var fileInfo = File.OpenBinaryDirect(_sharePointContext, pictureUrl); 
      using (var memory = new MemoryStream()) 
      { 
       var buffer = new byte[1000000]; 

       int nread; 
       while ((nread = fileInfo.Stream.Read(buffer, 0, buffer.Length)) > 0) 
       { 
        memory.Write(buffer, 0, nread); 
       } 
       memory.Seek(0, SeekOrigin.Begin); 

       var buffer2 = new byte[memory.Length]; 

       memory.Read(buffer2, 0, buffer2.Length); 
       return Convert.ToBase64String(buffer2); 
      } 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine($"Picture for user {email} can not be downloaded"); 
      Console.WriteLine(ex.Message); 
     } 
     return null; 
    } 

    private string GetPictureUrl(string email) 
    { 
     string targetUser = $"i:0#.f|membership|{email}"; 

     var peopleManager = new PeopleManager(_sharePointContext); 
     var personProperties = peopleManager.GetPropertiesFor(targetUser); 
     _sharePointContext.Load(personProperties, p => p.PictureUrl); 
     _sharePointContext.ExecuteQuery(); 
     var pictureUri = new Uri(personProperties.PictureUrl); 
     var localPath = pictureUri.LocalPath.Replace("MThumb", "LThumb"); //Change size of the picture 

     return localPath; 
    } 
1

Вы должны Microsoft Graph, чтобы получить изображение пользователя. https://graph.microsoft.com/v1.0/me/photo получает ваши метаданные о картинке профиля, а https://graph.microsoft.com/v1.0/me/photo/ $ value получает изображение. Вам нужно использовать OAuth. См. https://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/profilephoto_get для более подробной информации.

+0

Хорошо, спасибо. Я узнаю это. –

Смежные вопросы