使用 C# 卷曲请求API ProxMox

问题描述

无法将 C# 代码与 Unix 命令匹配 CURL 正确,响应正常,但 C# 是 {"data":null}

curl -k -d "username=test@pve&password=User11" https://ip:8006/api2/json/access/ticket

C#

string url = "https://ip:8006/api2/json/access/ticket";
WebRequest myReq = WebRequest.Create(url);
string username = "test@pve";
string password = "User11";
string usernamePassword = username + ":" + password;
CredentialCache mycache = new CredentialCache();
mycache.Add(new Uri(url),"Basic",new NetworkCredential(username,password));
myReq.Credentials = mycache;
myReq.Headers.Add("Authorization","Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream,Encoding.UTF8);
string content = reader.ReadToEnd();
Console.WriteLine(content);
Console.ReadLine();

回复:

{"data":null}

解决方法

谢谢Peter Csala,帮了大忙,我用过RestSharp

  static void Main(string[] args)
        {
            ServicePointManager.ServerCertificateValidationCallback = (senderX,certificate,chain,sslPolicyErrors) => { return true; };
            Run();
        }

        public static void Run() {
            var client = new RestClient("https://ip:8006/api2/json/access/ticket");

            var request = new RestRequest(Method.POST);

            request.AddParameter("username","test@pve");
            request.AddParameter("password","password");
            
            IRestResponse response = client.Execute(request);
            var settings = new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Include
            };

            dynamic stuff = JsonConvert.DeserializeObject(response.Content,settings);

            var array = stuff.data;

            string ticket = array.ticket.ToString();
            string CSRFPreventionToken = array.CSRFPreventionToken.ToString();

            //Call Nodes,VM,var clients = new RestClient("https://ip:8006/api2/json/nodes/pve01/qemu");

            client.Timeout = 10000;
            
            var requests = new RestRequest(Method.GET);
            requests.AddCookie("PVEAuthCookie",ticket);
            IRestResponse responses = clients.Execute(requests);

            var setting = new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore
            };

            dynamic stuffs = JsonConvert.DeserializeObject(responses.Content,setting);

            Console.WriteLine(stuffs);

            Console.ReadLine();
        }

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...