2015-01-20 25 views
15

Tôi phải gửi lệnh xóa tới dịch vụ REST API với nội dung JSON bằng cách sử dụng lớp HttpClient và không thể làm việc này.Làm thế nào để gửi DELETE với JSON tới REST API bằng cách sử dụng HttpClient

gọi API:

DELETE /xxx/current 
{ 
"authentication_token": "" 
} 

vì tôi không thể thêm bất kỳ nội dung vào tuyên bố dưới đây:

HttpResponseMessage response = client.DeleteAsync(requestUri).Result; 

Tôi biết làm thế nào để làm cho công việc này với RestSharp:

var request = new RestRequest { 
    Resource = "/xxx/current", 
    Method = Method.DELETE, 
    RequestFormat = DataFormat.Json 
}; 

var jsonPayload = JsonConvert.SerializeObject(cancelDto, Formatting.Indented); 

request.Parameters.Clear(); 
request.AddHeader("Content-type", "application/json"); 
request.AddHeader ("Accept", "application/json"); 
request.AddParameter ("application/json", jsonPayload, ParameterType.RequestBody); 

var response = await client.ExecuteTaskAsync (request); 

nhưng tôi đã hoàn thành công việc mà không cần RestSharp.

+0

(http://stackoverflow.com/questions/12022965/adding-http-headers-to-httpclient-asp-net -web-api) Ngoài ra, hãy xem bài viết MSDN cho [HttpRequestMessage] (http://msdn.microsoft.com/en-us/library/system.net.http.httprequestmessage (v = vs.118) .aspx). –

Trả lời

0

Hãy thử với

Sửa

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.your.url"); 

request.Method = "DELETE"; 

request.ContentType = "application/json"; 
request.Accept = "application/json"; 

using (var streamWriter = new StreamWriter(request.GetRequestStream())) 
{ 
    string json = "{\"key\":\"value\"}"; 

    streamWriter.Write(json); 
    streamWriter.Flush(); 
} 

using (var httpResponse = (HttpWebResponse)request.GetResponse()) 
{ 
    // do something with response 
} 

Here bạn có thể tìm thấy vấn đề rất giống nhau.

Edited
Tôi không chắc chắn rằng thông qua yêu cầu cơ thể cho DELETE yêu cầu là cách tiếp cận tốt. Đặc biệt khi điều này chỉ dành cho mục đích xác thực của bạn. Tôi muốn đặt authentication_token vào Tiêu đề. Đó là bởi vì trong giải pháp của tôi, tôi sẽ không phải phân tích toàn bộ phần thân yêu cầu để kiểm tra xem yêu cầu hiện tại có được xác thực chính xác hay không. Còn các loại yêu cầu khác thì sao? Bạn có luôn vượt qua authentication_token trong nội dung yêu cầu không?

24

Mặc dù có thể là muộn để trả lời câu hỏi này nhưng Tôi đã gặp phải sự cố tương tự và mã sau đây đã hoạt động đối với tôi.

HttpRequestMessage request = new HttpRequestMessage 
{ 
    Content = new StringContent("[YOUR JSON GOES HERE]", Encoding.UTF8, "application/json"), 
    Method = HttpMethod.Delete, 
    RequestUri = new Uri("[YOUR URL GOES HERE]") 
}; 
await httpClient.SendAsync(request); 
1

Câu trả lời từ Farzan Hajian vẫn không hiệu quả với tôi, tôi có thể đặt nội dung yêu cầu nhưng không thực sự được gửi đến máy chủ.

Thay vào đó, bạn có thể xem bằng cách sử dụng tiêu đề X-HTTP-Method-Override. Điều này cho máy chủ biết rằng bạn muốn nó xử lý yêu cầu như thể bạn đã gửi một động từ khác với động từ mà bạn thực sự gửi đi. Bạn sẽ phải đảm bảo rằng máy chủ xử lý tiêu đề này một cách chính xác, nhưng nếu nó bạn chỉ có thể POST yêu cầu và thêm: X-HTTP-Method-Override:DELETE vào các tiêu đề và nó sẽ tương đương với một yêu cầu DELETE với một phần thân.

14

Bạn có thể sử dụng các phương pháp khuyến nông: [. Nơi có thể xảy ra để bắt đầu]

public static class HttpClientExtensions 
{ 
    public static Task<HttpResponseMessage> DeleteAsJsonAsync<T>(this HttpClient httpClient, string requestUri, T data) 
     => httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Delete, requestUri) { Content = Serialize(data) }); 

    public static Task<HttpResponseMessage> DeleteAsJsonAsync<T>(this HttpClient httpClient, string requestUri, T data, CancellationToken cancellationToken) 
     => httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Delete, requestUri) { Content = Serialize(data) }, cancellationToken); 

    public static Task<HttpResponseMessage> DeleteAsJsonAsync<T>(this HttpClient httpClient, Uri requestUri, T data) 
     => httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Delete, requestUri) { Content = Serialize(data) }); 

    public static Task<HttpResponseMessage> DeleteAsJsonAsync<T>(this HttpClient httpClient, Uri requestUri, T data, CancellationToken cancellationToken) 
     => httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Delete, requestUri) { Content = Serialize(data) }, cancellationToken); 

    private static HttpContent Serialize(object data) => new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json"); 
} 
Các vấn đề liên quan