简体   繁体   English

将一段 javascript 代码转换为 c# 访问 API

[英]converting a piece of javascript code to c# access API

I need a C# code that will trigger a nprinting task.我需要一个将触发 nprinting 任务的 C# 代码。 On our server we are not allowed to evoke html file, hence I can't use javascript attached.在我们的服务器上,我们不允许调用 html 文件,因此我不能使用附加的 javascript。

The attached works just need to translate it to .net as I can't use html on our server所附作品只需将其翻译成 .net 因为我不能在我们的服务器上使用 html

Javascripts below works just fine下面的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# code which I can't complete all the below works but doesn't start the task. 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;

Thanks谢谢

I found a solution to the above, request.我找到了上述问题的解决方案,请求。 Nprinting API task to run from C# Nprinting API 任务从 C# 运行

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; }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM