【问题标题】:converting a piece of javascript code to c# access API将一段 javascript 代码转换为 c# 访问 API
【发布时间】:2020-08-13 23:25:19
【问题描述】:

我需要一个可以触发 nprinting 任务的 C# 代码。在我们的服务器上,我们不允许调用 html 文件,因此我不能使用附加的 javascript。

附加的作品只需要翻译成.net,因为我不能在我们的服务器上使用html

下面的 Javascript 可以正常工作

<html>
    <head>
    </head>
    <body>
        <h1>NPrinting API task starter</h1>
        <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
        <script type="text/javascript">
            (function(){
                console.log("started")
                var taskIDs=[
                    "f3ebd873-b310-4a22-a269-24ce81b8ce74"
                ]



                $.ajax({
                        url: 'URL:4993/api/v1/login/ntlm',
                        xhrFields: {
                            withCredentials: true
                        }
                    }).done(function(data) {
                        console.log(data);

                        for(var i=0;i<taskIDs.length;i++){
                            $.ajax({
                                type: "POST",
                                url: 'URL:4993/api/v1/tasks/'+taskIDs[i]+'/executions',
                                xhrFields: {
                                    withCredentials: true
                                }
                            }).done(function(data) {
                                console.log("task "+i);
                                console.log(data);
                                if(i==taskIDs.length)
                            open(location, '_self').close();
                            });
                        }
                    });
            })();
            <!-- open(location, '_self').close(); -->           
        </script>
    </body>
  </html>

我无法完成以下所有工作但无法启动任务的 C# 代码。

           //Create the HTTP Request (authenticate) and add required headers
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL:4993/api/v1/login/ntlm");
            CookieContainer cookies = new CookieContainer();
            request.CookieContainer = cookies;
            request.Method = "GET";
            request.UserAgent = "Windows";
            request.Accept = "application/json";
            // specify to run as the current Microsoft Windows user
            request.UseDefaultCredentials = true;
            try
            {
                // make the web request and return the content
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader responseReader = new StreamReader(response.GetResponseStream());
                string sResponseHTML = responseReader.ReadToEnd();
                Console.WriteLine(sResponseHTML);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }


//Create second HTTP request (get list of apps) and add required headers
            HttpWebRequest secondRequest = (HttpWebRequest)WebRequest.Create(@"URL:4993/api/v1/tasks/f3ebd873-b310-4a22-a269-24ce81b8ce74/executions");
            //assign cookie to request to maintain session
            secondRequest.CookieContainer = cookies;
            secondRequest.Method = "POST";
            secondRequest.UserAgent = "Windows";
            secondRequest.Accept = "application/json";
            // specify to run as the current Microsoft Windows user
            secondRequest.UseDefaultCredentials = true;

谢谢

【问题讨论】:

    标签: javascript c# api


    【解决方案1】:

    我找到了解决上述问题的方法,请求。 从 C# 运行的 Nprinting API 任务

    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Post_Request_API
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create the HTTP Request (authenticate) and add required headers
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"URL:4993/api/v1/login/ntlm");
                //Assign custom SSL certificate validation method if certificate is untrusted
                //request.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
                CookieContainer cookies = new CookieContainer();
                request.CookieContainer = cookies;
                request.Method = "GET";
                request.UserAgent = "Windows";
                request.Accept = "application/json";
                //Specify to run as the current Microsoft Windows user
                request.UseDefaultCredentials = true;
                try
                {
                    // make the web request and return the content
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    StreamReader responseReader = new StreamReader(response.GetResponseStream());
                    string sResponseHTML = responseReader.ReadToEnd();
                    Console.WriteLine(sResponseHTML);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                //Create second HTTP request to add a new user and required headers
                HttpWebRequest secondRequest = (HttpWebRequest)WebRequest.Create(@"URL:4993/api/v1/tasks/f3ebd873-b310-4a22-a269-24ce81b8ce74/executions");
                //Assign custom SSL certificate validation method if certificate is untrusted
                //secondRequest.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
                //Add the XSRF token
                secondRequest.Headers.Add("X-XSRF-TOKEN", cookies.GetCookies(request.RequestUri)["NPWEBCONSOLE_XSRF-TOKEN"].Value);
                secondRequest.CookieContainer = cookies;
                secondRequest.Method = "POST";
                secondRequest.UserAgent = "Windows";
                secondRequest.Accept = "application/json";
                secondRequest.ContentType = "application/json";
                //Specify to run as the current Microsoft Windows user
                secondRequest.UseDefaultCredentials = true;
    
                //Prepare JSON object to send to the remote server
                JsonUser user = new JsonUser();
                user.ID          = "";
                user.type        = "";
                user.task        = "";
                user.created     = "";
                user.lastUpdate  = "";
                user.completed   = "";
                user.progress    = "";
                user.status      = "Enqueued";
                user.result      = "";
                user.priority    = "";
    
    
                string jUserString = JsonConvert.SerializeObject(user);
                using (var streamWriter = new StreamWriter(secondRequest.GetRequestStream()))
                {
                    streamWriter.Write(jUserString);
                    streamWriter.Flush();
                    streamWriter.Close();
                }
                try
                {
                    HttpWebResponse response2 = (HttpWebResponse)secondRequest.GetResponse();
                    StreamReader responseReader2 = new StreamReader(response2.GetResponseStream());
                    string sResponseHTML2 = responseReader2.ReadToEnd();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
    
            public class JsonUser
            {
                public string ID        { get; set; }
                public string type      { get; set; }
                public string task      { get; set; }
                public string created   { get; set; }
                public string lastUpdate { get; set; }
                public string completed { get; set; }
                public string progress  { get; set; }
                public string status    { get; set; }
                public string result    { get; set; }
                public string priority  { get; set; }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-18
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多