如何正确发送PATCH请求

Lui*_*cia 10 c# rest azure adal

我需要调用这个REST端点

PATCH https://graph.windows.net/contoso.onmicrosoft.com/users/username@contoso.onmicrosoft.com?api-version=1.5 HTTP/1.1

{
    "<extensionPropertyName>": <value>
}
Run Code Online (Sandbox Code Playgroud)

请参阅此处的文档: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/usuario1@mysaasapp.onmicrosoft.com?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();
            }
        }
Run Code Online (Sandbox Code Playgroud)

然而,而不是respongint与204(没有内容),它响应整个用户属性,所以我想我的休息CALL有问题

http://screencast.com/t/LmoNswKIf2

小智 15

我认为你的问题是这一行:

HttpResponseMessage hrm = await hc.GetAsync(new Uri(requestUrl));
Run Code Online (Sandbox Code Playgroud)

这会向您提供的URL发送HTTP GET请求,在这种情况下引用用户"usuario1@mysaasapp.onmicrosoft.com".这就是您看到响应中返回的用户的所有属性的原因.

我想你想要做的是发送你创建的PATCH HttpRequestMessage.为此,您需要使用SendAsync方法并提供HttpRequestMessage作为参数.如果您将上面的行更改为以下内容,我认为您将设置属性值并获得204 No Content响应:

HttpResponseMessage hrm = await hc.SendAsync(request);
Run Code Online (Sandbox Code Playgroud)