2015-05-25 119 views
6

我需要調用這個REST端點如何正確發送PATCH請求

PATCH https://graph.windows.net/contoso.onmicrosoft.com/users/[email protected]?api-version=1.5 HTTP/1.1 

{ 
    "<extensionPropertyName>": <value> 
} 

請在這裏看到的文檔:https://msdn.microsoft.com/en-us/library/azure/dn720459.aspx

我有下面的代碼來設置一個屬性對用戶的價值:

public async Task<ActionResult> AddExtensionPropertyValueToUser() 
     { 
      Uri serviceRoot = new Uri(azureAdGraphApiEndPoint); 
      var token = await GetAppTokenAsync(); 
      string requestUrl = "https://graph.windows.net/mysaasapp.onmicrosoft.com/users/[email protected]?api-version=1.5"; 

      HttpClient hc = new HttpClient(); 
       hc.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); 

      var method = new HttpMethod("PATCH"); 

      var request = new HttpRequestMessage(method, requestUrl) 
      { 
       Content = new StringContent("{ \"extension_33e037a7b1aa42ab96936c22d01ca338_Compania\": \"Empresa1\" }", Encoding.UTF8, "application/json") 
      }; 

      HttpResponseMessage hrm = await hc.GetAsync(new Uri(requestUrl)); 
      if (hrm.IsSuccessStatusCode) 
      { 
       string jsonresult = await hrm.Content.ReadAsStringAsync(); 
       return View("TestRestCall", new SuccessViewModel 
       { 
        Name = "The Title", 
        Message = "The message", 
        JSON = jsonresult.ToJson() 
       }); 
      } 
      else 
      { 
       return View(); 
      } 
     } 

然而,而不是與204(無內容),它與整個用戶屬性響應respongint,所以我想的東西是錯誤與我的REST調用

http://screencast.com/t/LmoNswKIf2

+0

你提到你沒有得到的204,但被擴展屬性寫? –

回答

8

我覺得你的問題是這一行:

HttpResponseMessage hrm = await hc.GetAsync(new Uri(requestUrl)); 

這發送一個HTTP GET請求,您提供的網址,在這種情況下引用了用戶「[email protected] .COM」。這就是爲什麼你會看到響應中返回的用戶的所有屬性。

我想你想要做的就是發送你創建的PATCH HttpRequestMessage。爲此,您需要使用SendAsync方法並提供HttpRequestMessage作爲參數。如果更改上面的線以下,我想你會設置屬性值,讓你的204無內容迴應:

HttpResponseMessage hrm = await hc.SendAsync(request); 
+0

plus1爲catch,:) –

+0

嗨吉馬科,我使用sendAsync,但仍面臨的問題:任何指針? http://stackoverflow.com/questions/36023821/how-to-pass-the-following-json-to-a-c-sharp-patch-method-w-or-w-o-javascript-ser/36027802#36027802 –