将 PHP CURL 转换为 C#

Convert PHP CURL to C#

我正在尝试通过 C# 与 Web 服务的 api 通信,我有一个 php 代码,Curl 用来与客户端通信,但我想要整个 php curl代码要纯C#.

如何将下面的phpcurl代码转换成C#代码?

<?php
$url    = "http://localhost/";
$data   = "user=user1&pass=pass1";
$cookie = "00000000000000000000";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_COOKIE, $cookie);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_HEADER, 1);
$response = curl_exec($ch);
curl_close($ch);
?>
dynamic ch = null, cookie = null, url = null, var_response = null;
        url = new XVar("http://localhost/");
        data = new XVar("user=user1&pass=pass1");
        cookie = new XVar("00000000000000000000");
        ch = XVar.Clone(CommonFunctions.curl_init());
        CommonFunctions.curl_setopt((XVar)(ch), new XVar(Constants.CURLOPT_URL), (XVar)(url));
        CommonFunctions.curl_setopt((XVar)(ch), new XVar(Constants.CURLOPT_POSTFIELDS), (XVar)(data));
        CommonFunctions.curl_setopt((XVar)(ch), new XVar(Constants.CURLOPT_COOKIE), (XVar)(cookie));
        CommonFunctions.curl_setopt((XVar)(ch), new XVar(Constants.CURLOPT_RETURNTRANSFER), new XVar(1));
        CommonFunctions.curl_setopt((XVar)(ch), new XVar(Constants.CURLOPT_VERBOSE), new XVar(0));
        CommonFunctions.curl_setopt((XVar)(ch), new XVar(Constants.CURLOPT_HEADER), new XVar(1));
        var_response = XVar.Clone(CommonFunctions.curl_exec((XVar)(ch)));
        CommonFunctions.curl_close((XVar)(ch));
        return null;

您不需要专门发出 curl 请求。 cURL 在 php 中用作发出 http post 请求的简单方法。下面应该在 c# 中完成同样的事情。

var baseAddress = new Uri("http://localhost/");
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
    var content = new FormUrlEncodedContent(new[]
    {
        new KeyValuePair<string, string>("user", "user1"),
        new KeyValuePair<string, string>("pass", "pass1"),
    });

   cookieContainer.Add(baseAddress, new Cookie("CookieName", "cookie_value"));
   var result = await client.PostAsync(baseAddress, content);
   result.EnsureSuccessStatusCode();
}