2017-10-04 1 views
2

그룹에 구성원을 추가하려고합니다. 내 조직의 모든 그룹을 나열 할 수 있습니다. 전자 메일로 사용자를 얻고 모든 사용자를 얻으십시오. 그룹에서 구성원을 제거 할 수도 있습니다. 그러나 추가 할 수 없습니다. - 오류는 400 Bad Request입니다.그래프 REST AddMember to Group - Bad Request

I 신체 데이터 적어도 정확한 모습을 확인했다 (I는 accesstoken 유효 그룹 ID 및 유효 회원 ID가 수행) : 여기

작동하는 것과 동일한 기능 서명 인 함수 멀리 내가 example in the docs에서 볼 수 있습니다. 이것이 내가 할 필요가 마지막 호출입니다 - 나는 상황이 명확를 만들기 위해 추가 질문하고 내가 사람이 제공 할 수있는 어떤 도움

public async Task<string> AddGroupMember(string accessToken, string groupId, string memberId) 
{ 
    var status = string.Empty; 
    string endpoint = $"https://graph.microsoft.com/v1.0/groups/{groupId}/members/$ref"; 
    string queryParameter = ""; 

    // pass body data 
    var keyOdataId = "@odata.id"; 
    var valueODataId = $"https://graph.microsoft.com/v1.0/directoryObjects/{memberId}"; 

    var values = new List<KeyValuePair<string, string>> 
     { 
      new KeyValuePair<string, string>(keyOdataId, valueODataId) 
     }; 
    var body = new FormUrlEncodedContent(values); 

    try 
    { 
     using(var client = new HttpClient()) 
     { 
      using(var request = new HttpRequestMessage(HttpMethod.Post, endpoint + queryParameter)) 
      { 
       request.Content = body; 
       request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
       request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); 

       using(var response = await client.SendAsync(request)) 
       { 
        if (response.StatusCode == HttpStatusCode.NoContent) 
         status = "Member added to Group"; 
        else 
         status = $"Unable to add Member to Group: {response.StatusCode}"; 
       } 
      } 
     } 
    } 
    catch (Exception ex) 
    { 
     status = $"Error adding Member to Group: {ex.Message}"; 
    } 

    return status; 
} 

감사를 업데이트 할 수 있습니다 수있는 다른 어떤

확실하지 않음 다음 집에 무료

+0

미래를 알고 관심이있는에 대한 문제를 찾았 :

여기에 당신이있는 거 방법은 SDK를 사용하여 훨씬 더 간단 할 것이다 var에 몸을 = 새로운 FormUrl은 ... 코드가 올바르지 않습니다 = 새로운 StringContent VAR 몸체 ("{\" "+ keyOdataId +"\ ": \" "+ valueODataId +"\ "}", 인코딩, 필요한 것은이 변경 간단한 JSON 문자열 이다. UTF8, "application/json"); 일종의 clunky지만 작품 – Tab

답변

2

미래를 알고 관심있는 모든에 대한 문제 찾았 무엇이 필요

var body = new FormUrl... 내 코드가 잘못했다가, 간단한 JS입니다 문자열 갱신이 변경 :

var jsonData = [email protected]"{{ ""{keyOdataId}"": ""{valueODataId}"" }}"; var body = new StringContent(jsonData, Encoding.UTF8, "application/json");

내가 일반적으로 클래스의 값을 둘 것입니다하지만이 개념의 증명이며, JSON 키가 정확히 해명이 @odata.id

2

같이 할 필요가 현재 일어나고있는 일 :

이 요청 주체는 JSON (application/json)으로 인코딩되어야합니다. FormUrlEncodedContent 메서드는 사전을 Form encoded (application/x-www-form-urlencoded)로 반환합니다.

손으로 JSON을 작성할 수 있지만 더 좋은 해결책은 Json.NET을 활용하는 것입니다. 이것은 당신이 FormUrlEncodedContent 함께 있던 거의 같은 방법으로 당신에게 encode the dictionary을하게됩니다 :

var values = new Dictionary<string, string> 
    { 
     { keyOdataId, valueODataId} 
    }; 
var body = JsonConvert.SerializeObject(values); 

는 Microsoft 그래프와 함께 많은 작업을 수행 할 거라면, 나는 높은 Microsoft Graph .NET SDK로 전환에게 추천 할 것입니다.

public async Task<string> AddGroupMember(string groupId, string memberId) 
{ 
    GraphServiceClient graphClient = AuthenticationHelper.GetAuthenticatedClient(); 
    User userToAdd = new User { Id = memberId }; 
    await graphClient.Groups[groupId].Members.References.Request().AddAsync(userToAdd); 
} 
+0

나는 json.net 변환을 할거야 - 나는 미래의 애플 리케이션을위한 개념의 증거를 어떻게 모든 일을 볼 수 있습니다. SDK가 더 쉽게 보입니다. 팁 덕분에 응답 해 주셔서 감사 드리며 실제 거래 할 때 보게됩니다. – Tab

+0

단순히 '값'var를 변환하는 것은 승자가 아닙니다. '[{Key : "@ odata.id", "Value": "https://graph.microsoft.com/v1.0 @의 odata.id ":"https://graph.microsoft.com/v1.0/ :/directoryObjects은/ee32df9c-6acc-453c-abb2-afb4380e364d " '{ }]' 는 다음과 같이해야" " }" 둘째, 몸체에 문자열이 아닌 StringContent 유형이 필요하므로 콜렉션을 '본문'으로 직렬화 할 수 없습니다. – Tab

+0

죄송합니다. 잘못된 라인을 복사하여 붙여 넣습니다. List 대신 Dictionary 을 사용해야합니다. –

관련 문제