简体   繁体   English

如何通过 C# WebClient 发送 HTTP DELETE 请求?

[英]How to send HTTP DELETE Request via C# WebClient?

After logging in I can have a token from my remote system.登录后,我可以从我的远程系统获得一个令牌。 For example the authentication_token is 8JySqFVx_pKx_3nx67AJ I can log out from terminal via this command例如 authentication_token 是 8JySqFVx_pKx_3nx67AJ 我可以通过这个命令从终端注销

curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X DELETE https://sample.com\?authentication_token\=8JySqFVx_pKx_3nx67AJ

I need to do it from C#. I can send POST request like this:我需要从 C# 开始。我可以像这样发送 POST 请求:

        WebClient wc = new WebClient();
        string baseSiteString = wc.DownloadString("https://sample.com");
        string csrfToken = Regex.Match(baseSiteString, "<meta name=\"csrf-token\" content=\"(.*?)\" />").Groups[1].Value;
        string cookie = wc.ResponseHeaders[HttpResponseHeader.SetCookie];

        wc.Headers.Add(HttpRequestHeader.Cookie, cookie);
        wc.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");
        wc.Headers.Add(HttpRequestHeader.Accept, "application/json, text/javascript, */*; q=0.01");
        wc.Headers.Add("X-CSRF-Token", csrfToken);
        wc.Headers.Add("X-Requested-With", "XMLHttpRequest");


        string dataString  =  @"{""user"":{""email"":""sample@sample.com"",""password"":""sample_password""}}";
        byte[] dataBytes = Encoding.UTF8.GetBytes(dataString);
        byte[] responseBytes = wc.UploadData(new Uri("https://sample.com/auth.json"), "POST", dataBytes);
        string responseString = Encoding.UTF8.GetString(responseBytes);

How Can I send DELETE request from C# where authentication_token would be a parameter?如何从 C# 发送 DELETE 请求,其中 authentication_token 将是一个参数?

Solved, I used WebClient. 解决了,我使用了WebClient。

        var wc2 = new WebClient();
        string baseSiteString2 = wc2.DownloadString("https://sample.com");
        string csrfToken2 = Regex.Match(baseSiteString2, "<meta name=\"csrf-token\" content=\"(.*?)\" />").Groups[1].Value;
        string cookie2 = wc2.ResponseHeaders[HttpResponseHeader.SetCookie];

        wc2.Headers.Add(HttpRequestHeader.Cookie, cookie2);
        wc2.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");
        wc2.Headers.Add(HttpRequestHeader.Accept, "application/json, text/javascript, */*; q=0.01");
        wc2.Headers.Add("X-CSRF-Token", csrfToken2);
        wc2.Headers.Add("X-Requested-With", "XMLHttpRequest");


        string dataString2 = "";// @"{""name"":""Megan"",""regi_number"":4444}";
        byte[] dataBytes2 = Encoding.UTF8.GetBytes(dataString2);
        string finalUrl = "https://sample.com?authentication_token=" + authentication_token;
        byte[] responseBytes2 = wc2.UploadData(new Uri(finalUrl), "DELETE", dataBytes2);
        string responseString2 = Encoding.UTF8.GetString(responseBytes2);
        authentication_token = "";         

Why not use the much simpler HttpClient for this job? 为什么不使用更简单的HttpClient来完成这项工作? (Your existing code to post via http could be heavely improved/simplyfied by using the HttpClient) (使用HttpClient可以大大改善/简化通过HTTP发布的现有代码)

You could do something like this: 您可以执行以下操作:

private HttpClient GetHttpClient()
{
    // Initialize client with default headers, base address, etc.
    var httpClient = new HttpClient();
    httpClient.BaseAddress = new Uri("https://sample.com");
    httpClient.DefaultRequestHeaders.Accept.Clear();
    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    // Set some other headers if necessary...

    return httpClient;
}

private async Task DeleteUser(string token)
{
    using (var httpClient = GetHttpClient())
        await httpClient.DeleteAsync("api/users/delete?token=" + token);
}

The above is async though, (as everything is in the HttpClient class. You could however create a synchronous method like this: 上面是异步的,(因为所有内容都在HttpClient类中。但是,您可以创建一个这样的同步方法:

private void DeleteUser(string token)
{
    using (var httpClient = GetHttpClient())
        httpClient.DeleteAsync("api/users/delete?token=" + token).Result;
}

You don't really need to use a WebClient for sending a DELETE request.您实际上不需要使用WebClient来发送DELETE请求。 I use a simple HttpWebRequest like so:我像这样使用简单的HttpWebRequest

var url = "https://yourwebservice";

var httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Method = "DELETE";
httpRequest.Accept = "*/*";
httpRequest.Headers["Authorization"] = "yourauth";

var httpResponse = (HttpWebResponse)httpRequest.GetResponse();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM