在 C# 中模拟 Curl --user --insecure

Emulating Curl --user --insecure in c#

我有以下有效的 Curl 调用。

curl --insecure --user user@applicationname:password "https://someURL"

我这辈子都无法让 HttpWebRequest 模拟这个。

目前我正在尝试

 var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://someURL);
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Accept = "*/*";
        httpWebRequest.Method = "POST";
        httpWebRequest.Headers["Authorization"] = "Basic " +    Convert.ToBase64String(Encoding.ASCII.GetBytes("USER@Account:Password"));

我收到错误身份验证失败,因为远程方已关闭传输流

我猜这与具有不安全选项的 curl 命令有关,但我无法在我的生活中看到如何在请求中执行此操作。

做网络 restrictions/policies 我无法下载 restSharp 或任何其他第 3 方库...

在执行请求之前添加这一行

System.Net.ServicePointManager.ServerCertificateValidationCallback = (obj, X509certificate, chain, errors) => true;

我最终改用了 HttpClient。结合使用从上面的@Alberto Monteiro 获得的信息,我能够让我的代码按预期工作。

        string url = Request.Form["Url"];

        using (var client = new HttpClient())
        {
             ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;

             ServicePointManager.ServerCertificateValidationCallback = (obj, x509Certificate, chain, errors) => true;

            client.BaseAddress = new Uri(url);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
                new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("text/xml"));

            var byteArray = Encoding.ASCII.GetBytes(Request.Form["User"] + "@ACCOUNT:" + Request.Form["Pass"]);
            var header = new AuthenticationHeaderValue(
                "Basic", Convert.ToBase64String(byteArray));
            client.DefaultRequestHeaders.Authorization = header;

            var response = client.GetAsync(url).Result;
            HttpContent content = response.Content;
            string result = content.ReadAsStringAsync().Result;

        }