2014-10-06 13 views

Odpowiedz

39

znalazłem jak zrobić „zwyczaj” PATCH wniosek z poprzedniego System.Net.Http.HttpClient klasy here, a potem bawił się aż zrobiłem to działa w klasie Windows.Web.Http.HttpClient, tak:

public async Task<HttpResponseMessage> PatchAsync(HttpClient client, Uri requestUri, IHttpContent iContent) { 
    var method = new HttpMethod("PATCH"); 

    var request = new HttpRequestMessage(method, requestUri) { 
     Content = iContent 
    }; 

    HttpResponseMessage response = new HttpResponseMessage(); 
    // In case you want to set a timeout 
    //CancellationToken cancellationToken = new CancellationTokenSource(60).Token; 

    try { 
     response = await client.SendRequestAsync(request); 
     // If you want to use the timeout you set 
     //response = await client.SendRequestAsync(request).AsTask(cancellationToken); 
    } catch(TaskCanceledException e) { 
     Debug.WriteLine("ERROR: " + e.ToString()); 
    } 

    return response; 
} 
+0

zamiast '' ' Odpowiedź HttpResponseMessage = new HttpResponseMessage(); '' ' użyj ' '' var response = default (HttpResponseMessage); '' ' – Wilmer

29

można napisać Ta sama metoda jak metoda rozszerzenie, dzięki czemu można powoływać się bezpośrednio na obiekcie httpclient:

public static class HttpClientExtensions 
{ 
    public static async Task<HttpResponseMessage> PatchAsync(this HttpClient client, Uri requestUri, HttpContent iContent) 
    { 
     var method = new HttpMethod("PATCH"); 
     var request = new HttpRequestMessage(method, requestUri) 
     { 
      Content = iContent 
     }; 

     HttpResponseMessage response = new HttpResponseMessage(); 
     try 
     { 
      response = await client.SendAsync(request); 
     } 
     catch (TaskCanceledException e) 
     { 
      Debug.WriteLine("ERROR: " + e.ToString()); 
     } 

     return response; 
    } 
} 

Zastosowanie:

var responseMessage = await httpClient.PatchAsync(new Uri("testUri"), httpContent); 
+0

jak przekazać zawartość? –

+4

Widzisz drugi parametr? Spróbuj czegoś takiego: 'HttpContent httpContent = new StringContent (" Twój JSON-String ", Encoding.UTF8," application/json ");' dla String-Contents. –

+0

Popraw mnie, jeśli się mylę, ale metoda PATCH oznacza, że ​​modyfikujesz tylko określone dane w JSON. Jak modyfikujesz, powiedzmy, tylko nazwę produktu? Jeśli przez "Twój JSON-String" rozumiesz cały JSON, to jestem zdezorientowany. Próbowałem dodać jedną właściwość, taką jak 'HttpContent content = new StringContent (" {\ "name \": \ "John Doe \" ", Encoding.UTF8," application/json ");' ale zawartość nie jest dodana do wniosku. – Caloyski

10

Chciałbym rozszerzyć odpowiedź @ alexander-pacha i zasugerować dodanie następnej klasy rozszerzenia gdzieś we wspólnej bibliotece. Czy jest to wspólna biblioteka dla projektu/klienta/frameworka/... jest czymś, co sam musisz sobie wyobrazić.

public static class HttpClientExtensions 
    { 
     /// <summary> 
     /// Send a PATCH request to the specified Uri as an asynchronous operation. 
     /// </summary> 
     /// 
     /// <returns> 
     /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation. 
     /// </returns> 
     /// <param name="client">The instantiated Http Client <see cref="HttpClient"/></param> 
     /// <param name="requestUri">The Uri the request is sent to.</param> 
     /// <param name="content">The HTTP request content sent to the server.</param> 
     /// <exception cref="T:System.ArgumentNullException">The <paramref name="client"/> was null.</exception> 
     /// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception> 
     public static Task<HttpResponseMessage> PatchAsync(this HttpClient client, string requestUri, HttpContent content) 
     { 
      return client.PatchAsync(CreateUri(requestUri), content); 
     } 

     /// <summary> 
     /// Send a PATCH request to the specified Uri as an asynchronous operation. 
     /// </summary> 
     /// 
     /// <returns> 
     /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation. 
     /// </returns> 
     /// <param name="client">The instantiated Http Client <see cref="HttpClient"/></param> 
     /// <param name="requestUri">The Uri the request is sent to.</param> 
     /// <param name="content">The HTTP request content sent to the server.</param> 
     /// <exception cref="T:System.ArgumentNullException">The <paramref name="client"/> was null.</exception> 
     /// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception> 
     public static Task<HttpResponseMessage> PatchAsync(this HttpClient client, Uri requestUri, HttpContent content) 
     { 
      return client.PatchAsync(requestUri, content, CancellationToken.None); 
     } 
     /// <summary> 
     /// Send a PATCH request with a cancellation token as an asynchronous operation. 
     /// </summary> 
     /// 
     /// <returns> 
     /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation. 
     /// </returns> 
     /// <param name="client">The instantiated Http Client <see cref="HttpClient"/></param> 
     /// <param name="requestUri">The Uri the request is sent to.</param> 
     /// <param name="content">The HTTP request content sent to the server.</param> 
     /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> 
     /// <exception cref="T:System.ArgumentNullException">The <paramref name="client"/> was null.</exception> 
     /// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception> 
     public static Task<HttpResponseMessage> PatchAsync(this HttpClient client, string requestUri, HttpContent content, CancellationToken cancellationToken) 
     { 
      return client.PatchAsync(CreateUri(requestUri), content, cancellationToken); 
     } 

     /// <summary> 
     /// Send a PATCH request with a cancellation token as an asynchronous operation. 
     /// </summary> 
     /// 
     /// <returns> 
     /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation. 
     /// </returns> 
     /// <param name="client">The instantiated Http Client <see cref="HttpClient"/></param> 
     /// <param name="requestUri">The Uri the request is sent to.</param> 
     /// <param name="content">The HTTP request content sent to the server.</param> 
     /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> 
     /// <exception cref="T:System.ArgumentNullException">The <paramref name="client"/> was null.</exception> 
     /// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception> 
     public static Task<HttpResponseMessage> PatchAsync(this HttpClient client, Uri requestUri, HttpContent content, CancellationToken cancellationToken) 
     { 
      return client.SendAsync(new HttpRequestMessage(new HttpMethod("PATCH"), requestUri) 
      { 
       Content = content 
      }, cancellationToken); 
     } 

     private static Uri CreateUri(string uri) 
     { 
      return string.IsNullOrEmpty(uri) ? null : new Uri(uri, UriKind.RelativeOrAbsolute); 
     } 
    } 

ten sposób nie jesteś w oczekiwaniu na wykonanie i trzyma się w jakiejś klasie statycznej przedłużacza, ale sobie z tym poradzić, jak gdybyś naprawdę robi PostAsync lub połączenia PutAsync. Masz również do dyspozycji te same przeciążenia i pozwalasz HttpClientowi obsłużyć wszystko, co zaprojektowałeś.

+0

To wygląda świetnie. Powinieneś rozważyć utworzenie Pull-Request z nim na Github w oficjalnym repozytorium .NET Framework, ponieważ oczekują wpłat: https://github.com/dotnet/corefx/blob/master/src/System.Net.Http /src/System/Net/Http/HttpClient.cs –

+0

Edytuj: Ktoś mnie pobił, został dodany do repo, z którym łączy cię ktoś inny. –

0

go do pracy trzeba przekazać treść tak:

HttpContent httpContent = new StringContent ("Twój JSON-String", Encoding.UTF8 "application/json-łata + json");

Powiązane problemy