C# WebClient 宁静删除
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12376974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WebClient restful Delete
提问by Jimmy James
I have a simple Restful service being called from a console app so am using WebClient. I am wondering if this call for Delete is correct.
我有一个从控制台应用程序调用的简单 Restful 服务,因此正在使用 WebClient。我想知道这个删除的调用是否正确。
The url looks like localhost/RestService1/Person/1
网址看起来像localhost/RestService1/Person/1
using (var client = new WebClient())
{
client.UploadString(url, "DELETE", "");
}
I don't like that UploadString does not have an overload without a data parameter. The passing of an empty parameter is not sitting well with me. Is there a better method to use for a "DELETE"?
我不喜欢 UploadString 没有没有数据参数的重载。传递空参数对我来说不太合适。有没有更好的方法用于“删除”?
I could use WebRequest but I want to just use WebClient to keep it consistent.
我可以使用 WebRequest 但我只想使用 WebClient 来保持它的一致性。
Here is the WebRequest block
这是 WebRequest 块
var request = WebRequest.Create(url);
request.Method = "DELETE";
var response = (HttpWebResponse)request.GetResponse();
Both blocks work fine but what is best? Or is there a better way?
两个块都可以正常工作,但什么是最好的?或者,还有更好的方法?
回答by RTigger
The WebClient class doesn't really lend well to restful api consumption, I've used 3rd party libraries like RestSharpin the past that are geared more towards this type of web request. I'm pretty sure RestSharp just uses HttpWebRequest under the covers, but it provides a lot of semantics that make consuming and reusing rest resources easier.
WebClient 类并不能很好地用于Restfulapi 消费,我过去使用过像RestSharp这样的 3rd 方库,它们更适合这种类型的 Web 请求。我很确定 RestSharp 只是在幕后使用 HttpWebRequest,但它提供了很多语义,使消耗和重用休息资源更容易。
回答by Darrel Miller
Go get the Microsoft.Net.Http client libraries http://nuget.org/packages/Microsoft.Net.Http
去获取 Microsoft.Net.Http 客户端库http://nuget.org/packages/Microsoft.Net.Http
HttpClient is a much better client to use for working with an API.
HttpClient 是用于处理 API 的更好的客户端。
回答by Simon
The following works for me:
以下对我有用:
client.UploadValues(url, "DELETE", new NameValueCollection());

