【问题标题】:How to use cURL in ASP.NET with Cookie File如何在 ASP.NET 中通过 Cookie 文件使用 cURL
【发布时间】:2016-07-06 18:14:51
【问题描述】:

我正在使用一个硬件设备并想对其进行一些操作。

目前它使用 cURL 来执行操作。但是我想在 ASP.NET Web 表单应用程序中做同样的事情,下面是设备使用的 CURL 命令:

1) 首先,我必须将用户身份验证存储在 cookie 文件中:

curl -1 -v -L -k -c cookie.txt  -d save=2 -d adm_name=admin -d adm_pwd=admin  https://10.71.1.111/check.shtml

这家店cookie.txt在我的文件夹里。

2) 现在我必须运行第二个命令来执行主要操作(在这种情况下为创建用户)

curl -1 -v -L -k -b cookie.txt -d save=1 -d U1=michael -d P1=abcd1234 -d M1=00:09:6B:CD:88:00 -d C1=d -d R1=FinanceDep https:// 10.71.1.111/UserAuthentication/AddUser.shtml 

这里我发送cookie.txt 文件来创建用户。在这个命令中U1、P1、M1、C1、R1是参数。

谁能帮我从 ASP.NET 做同样的事情

问候 桑塔努

编辑:

根据给出的答案,我在 VB.NET 中转换了代码并使用了它,但不幸的是它也没有给出任何错误并返回任何响应

Dim jar As New CookieContainer()

        Dim target As New Uri("https://x.x.x.x/check.shtml")

        'jar.Add(New Cookie("adm", "admin"))
        'jar.Add(New Cookie("admpwd", "6e49b5b6c16eff37c0d8217382fe1c7e"))
        'jar.Add(New Cookie("first_login_home_page", "home.shtml"))
        'jar.Add(New Cookie("name", "value"))

        jar.Add(New Uri("https://x.x.x.x/check.shtml"), New Cookie("adm", "admin"))
        jar.Add(New Uri("https://x.x.x.x/check.shtml"), New Cookie("admpwd", "6e49b5b6c16eff37c0d8217382fe1c7e"))
        jar.Add(New Uri("https://x.x.x.x/check.shtml"), New Cookie("first_login_home_page", "home.shtml"))

        Dim request As HttpWebRequest = DirectCast(WebRequest.Create("https://x.x.x.x/UserAuthentication/AddUser.shtml"), HttpWebRequest)

        request.CookieContainer = jar
        request.AllowAutoRedirect = True
        ' request.ServerCertificateValidationCallback = AddressOf AcceptAllCertifications

        ServicePointManager.ServerCertificateValidationCallback = New RemoteCertificateValidationCallback(Function() True)


        request.Method = "POST"

        Dim fields As New NameValueCollection()
        fields.Add("save", "1")
        fields.Add("U1", "michael")
        fields.Add("P1", "abcd1234")
        fields.Add("C1", "1")
        fields.Add("R1", "FinanceDep")



        Using requestBody As Stream = request.GetRequestStream()
            Using wtr As New StreamWriter(requestBody, Encoding.ASCII)
                Dim first As [Boolean] = True
                For Each key As [String] In fields.Keys
                    If Not first Then
                        wtr.Write("&"c)
                    End If
                    Dim keyEnc As [String] = HttpUtility.UrlEncode(key)
                    Dim valEnc As [String] = HttpUtility.UrlEncode(fields(key))

                    wtr.Write(keyEnc)
                    wtr.Write("="c)
                    wtr.Write(valEnc)
                    first = False
                Next
            End Using
        End Using


        Dim response As HttpWebResponse = Nothing

        Try
            response = request.GetResponse()
        Catch wex As WebException
            If wex.Response IsNot Nothing Then
                response = wex.Response
            End If
        End Try

【问题讨论】:

    标签: asp.net curl cookies


    【解决方案1】:

    对于发出 HTTP 请求,.NET 有三个选项:

    • HttpWebRequest - 带有阻塞 API 的简单单一请求/响应。
    • HttpClient- 在 .NET 4 中引入,具有 async API。
    • WebClient - 围绕 HttpWebRequest 的有状态包装器。我不建议使用它。

    我个人的偏好是使用HttpWebRequest,因为我发现在阻塞调用很丑的情况下处理异步调用,并且相对简单:

    你的卷曲选项是:

    -1     Force TLS
    -v     Verbose
    -L     Follow HTTP Location: header in redirections
    -k     Disables TLS certificate CA checking
    -c     Specify cookie jar file
    -d     Specify request body form fields and use `application/x-www-form-urlencoded`
    

    这可以像这样转换为HttpWebRequest:

    CookieContainer jar = new CookieContainer();
    jar.Add( new Cookie("name", "value") );
    
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://10.71.1.111/check.shtml");
    request.CookieContainer = jar;
    request.AllowAutoRedirect = true;
    request.ServerCertificateValidationCallback += delegate(sender, certificate, chain, sslPolicyErrors) {
        return true; // ignore all certificate errors
    };
    request.Method = "POST";
    
    NameValueCollection fields = new NameValueCollection();
    fields.Add("save", "2");
    fields.Add("adm_name", "admin");
    fields.Add("adm_pwd", "admin");
    fields.Add("U1", "michael");
    
    // Set request body
    using(Stream requestBody = request.GetRequestStream())
    using(StreamWriter wtr = new StreamWriter( requestBody, Encoding.ASCII ) ) {
        Boolean first = true;
        foreach(String key in fields.Keys) {
            if( !first ) wtr.Write('&');
            String keyEnc = HttpUtility.UrlEncode( key );
            String valEnc = HttpUtility.UrlEncode( fields[key] );
    
            wtr.Write( keyEnc );
            wtr.Write('=');
            wtr.Write( valEnc );
            first = false;
        }
    }
    
    HttpWebResponse response = null;
    try {
        response = request.GetResponse();
    } catch(WebException wex) {
        if( wex.Response != null ) response = wex.Response;
    }
    
    // do stuff with response
    

    请注意,-1 选项不适用,因为HttpWebRequest 将使用系统范围的 TLS 设置,并且由于它使用 https:// 方案进行连接,因此不会回退到纯 HTTP。

    我看到您正在使用文件系统中存在的 cookie 文件。您需要将相同的内容放入jar 变量中。我提供了一个示例 cookie (Name:Value)。

    将AllowAutoRedirect 属性设置为true 是不必要的,因为这是属性默认值。

    最后,其余代码获取每个键+名称对,并通过 URL 将其编码到请求正文中。我同意这很复杂,我很惊讶HttpWebRequest 没有提供一种简单的方法来生成 URL 编码的请求正文。

    【讨论】:

    • 亲爱的 Dai,感谢您的解决方案,我有两个疑问 1) 您将此请求发送到 10.71.1.111/check.shtml 我从中获取身份验证但不是 https://10.71.1.111/UserAuthentication /AddUser.shtml 设备实际创建用户的位置。我会直接触发 https://10.71.1.111/UserAuthentication/AddUser.shtml 2) 如果我直接触发 https://10.71.1.111/UserAuthentication/AddUser.shtml 那么它将如何获取 cookie 或者它将自动创建它。很抱歉问你这个问题,但我是新手,所以问同样的问题。
    • 我绑定了上面的代码,但它在 response = request.GetResponse(); 上不起作用它返回 NULL
    • @SantanuDas GetResponse 永远不会返回 null,它会在出现错误时抛出异常。调试您的代码并观察任何抛出的异常。
    猜你喜欢
    • 2013-05-15
    • 2011-08-25
    • 1970-01-01
    • 2021-12-24
    • 2011-05-07
    • 1970-01-01
    • 2015-10-17
    • 1970-01-01
    • 2013-02-18
    相关资源
    最近更新 更多