【问题标题】:How to convert this curl command to c#?如何将此 curl 命令转换为 c#?
【发布时间】:2019-03-25 04:55:41
【问题描述】:

curl -x http://ip:port -key mykey.key -cert mycert.cert https://url -h "exampleheader:examplevalue"

【问题讨论】:

  • 请详细说明。 convert command to C# 是什么意思?
  • @HosseinGolshani 我们的客户提供 API 服务来获取令牌。此 API 请求在调用时需要我们的 SSL 客户端证书和 privateKey。该请求如下所示 curl -x ProxyIP:Port -v --key MyPrivateKey.key --cert MyCertificate.crt clientrequestURL -H "Headerkey:HeaderKeyValue" 这是我们的 Curl 请求。我需要这个请求这个在 c# 中的查询。我尝试了很多方法,但每次都会出现 401 access denied 错误。你能帮忙吗?

标签: c# azure curl asp.net-web-api azure-devops-rest-api


【解决方案1】:

你可以试试这样的

更新代码

// Use this if you are in a web context
// var certificatePath = System.Web.HttpContext.Current.Server.MapPath(
//                  "your_client_certificate_path"),

// Use this in a non web context. 
// certificatePath should be the same value as the parameter you are using 
// in your command line
//  -cert mycert.cert   <------ This one
var certificatePath = "your_physical_path_file_to_mycert.cert";

// Certificate from file 
var _clientCertificate = new X509Certificate2(
                          certificatePath,
                          "your_client_certificate_key");

// Web handler
var handler = new System.Net.Http.WebRequestHandler();
handler.ClientCertificates.Add(_clientCertificate);

// Http Client
var _httpClient = new System.Net.Http.HttpClient(handler);
_httpClient.DefaultRequestHeaders.Add("Header Key", "Header Value");

// Requests
_httpClient.GetAsync("your_request_URI");

【讨论】:

  • 谢谢阿尔弗雷多。但它不起作用。我得到 Object reference not set to an instance of an object. 错误 var _clientCertificate = new X509Certificate2(System.Web.HttpContext.Current.Server.MapPath("your_client_certificate_path") , "your_client_certificate_key");
  • System.Web.HttpContext.Current.Server.MapPath("your_client_certificate_path") 用于 Web 上下文,如果您不在 Asp. NET 应用程序将无法正常工作。你在什么情况下?这个想法是让您获取文件的物理路径
  • 我正在创建 .net 窗口应用程序以获取 SAS 令牌。
  • X509Certificate2 构造函数有两个参数,第一个是您的证书的财政路径。它只是一个字符串,例如"C:\MyCertificates\mycert.cert" 之类的内容,您应该提供文件的路径。你到底得到了什么错误? 对象引用未设置为对象的实例。 被抛出,因为您正在使用 ystem.Web.HttpContext.Current.Server.MapPathSystem.Web .HttpContext.Currentnull 因为您不在网络上下文中,但该行只是作为示例放置以获取证书文件的物理路径。
  • "your_client_certificate_key" 是什么意思?私钥还是证书密码?如果它的意思是私钥我应该给什么?私钥文件路径或私钥文件内容字符串。
猜你喜欢
  • 1970-01-01
  • 2016-09-08
  • 2021-10-08
  • 2012-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多