简体   繁体   中英

C# LibCurlNet , keeping the same session id in Cookie.txt

I am a beginner C# developer and I'm a bit stuck.

I have a project where I need to keep the same session ID cookie when making HTTP requests. The requests work fine, i create what i need to in the API (its a currency exchange API). the problem is when i create a payment to buy lets say 100 pounds i go to a screen where i need to authorise the payment. In here i have a exchange rate that is valid for 1.5 minute. when the time ends the rates refreshes. To lock the rates i need to authorise the payment. When i Authorise i go to the screen waiting for payments. Here the rate is now locked but the problem is that the rate is not the same that i locked. The owned of the website told me that it is because the session ID was not the same on the request to create the payment and authorise.

This is from the API documentation:

API connection can be established via HttpsRequest components like cURL. If cURL library is not available in desired language version then the alternative should provide as follows:

  1. All cURL queries/requests/data transfer should use HTTPS protocol only.
  2. All sensitive information must be sent by POST method;
  3. SSL certificate and SSL host verification. It will prevent DNS hack attack.See CURLOPT_SSL_VERIFYHOST & CURLOPT_SSL_VERIFYPEER
  4. Session and cookie support;

The example code I found was in PHP using Curl. This is what I came up with using LibCurlNet:

public class Http
{
     string _xmlResponse = string.Empty;

     private static Easy easy;
     private static Easy.WriteFunction wf = null;




    public string PerformRequest(string xml, string queryString, string url)
    {

        try
        {
            _xmlResponse = string.Empty;
            Curl.GlobalInit((int)CURLinitFlag.CURL_GLOBAL_ALL);
            easy = new Easy();

            wf = new Easy.WriteFunction(OnWriteData);
            easy.SetOpt(CURLoption.CURLOPT_URL, url);
            easy.SetOpt(CURLoption.CURLOPT_WRITEFUNCTION, wf);
            easy.SetOpt(CURLoption.CURLOPT_COOKIEFILE, HttpContext.Current.Request.MapPath("~/cookies.txt"));
            easy.SetOpt(CURLoption.CURLOPT_COOKIEJAR, HttpContext.Current.Request.MapPath("~/cookies.txt"));



            easy.SetOpt(CURLoption.CURLOPT_SSL_VERIFYPEER, true);
            easy.SetOpt(CURLoption.CURLOPT_SSL_VERIFYHOST, true);
            easy.SetOpt(CURLoption.CURLOPT_CAINFO, HttpContext.Current.Request.MapPath("~/ssl.crt"));
            easy.SetOpt(CURLoption.CURLOPT_HEADER, 0);
            easy.SetOpt(CURLoption.CURLOPT_FOLLOWLOCATION, true);
            easy.SetOpt(CURLoption.CURLOPT_USERAGENT, "xxx Web XML API");

            easy.SetOpt(CURLoption.CURLOPT_BUFFERSIZE, 65536);
            easy.SetOpt(CURLoption.CURLOPT_POSTFIELDS, CleanXML(xml));
            easy.Perform();
            easy.Cleanup();

            Curl.GlobalCleanup();
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
        return _xmlResponse;
    }

    public Int32 OnWriteData(Byte[] buf, Int32 size, Int32 nmemb,
        Object extraData)
    {
        _xmlResponse = _xmlResponse + System.Text.Encoding.UTF8.GetString(buf);

        return size * nmemb;
    }

    private string CleanXML(string xml)
    {

        char[] sep = Environment.NewLine.ToArray();
        string[] lines = xml.Split(sep);
        StringBuilder sb = new StringBuilder();
        foreach (string line in lines)
        {
            sb.Append(line.Trim());
        }
        return sb.ToString();
    }

}

The problem is that the cookie.txt updates the session ID with every connection I make.

Code with HttpWebRequest:

public class HttpV2
{
   static CookieCollection cookie = new CookieCollection();
   string responseFromServer;
   public string GetHttpResponse(string Url, string requestBody)
   {



       //WebRequest request = WebRequest.Create(Url);

       HttpWebRequest request = HttpWebRequest.CreateHttp(Url);

        X509Certificate Cert = X509Certificate.CreateFromCertFile(@"D:\www_root\xxxxxxxxxxx\xxxxx\ssl.crt");
        request.ClientCertificates.Add(Cert);
        request.Method = "POST";


       //HttpContext context = HttpContext.Current;
       request.CookieContainer = new CookieContainer();
       request.UserAgent = "TranferMate Web XML API";
       if (cookie != null)
       {

           request.CookieContainer.Add(cookie);

       }
       byte[] byteArray = Encoding.UTF8.GetBytes(requestBody);
       request.ContentType = "application/x-www-form-urlencoded";
       request.ContentLength = byteArray.Length;

       Stream dataStream = request.GetRequestStream();
       dataStream.Write(byteArray, 0, byteArray.Length);
       dataStream.Close();

       #region Get the response.
       using (WebResponse response = request.GetResponse())
       {
           if (requestBody.Contains("<FORCE_REFRESH>1</FORCE_REFRESH>"))
           {
               cookie = ((HttpWebResponse)response).Cookies;
           }
           if (((HttpWebResponse)response).StatusCode == HttpStatusCode.OK)
               using (Stream stream = response.GetResponseStream())
               {
                   if (stream != null)
                   {
                       using (StreamReader reader = new StreamReader(stream))
                       {
                           responseFromServer = reader.ReadToEnd();

                           reader.Close();
                       }
                       stream.Close();
                   }
               }
           response.Close();
       }
       #endregion

       return responseFromServer;
   }
}

Instead of using Curl could you not use the built-in HttpWebRequest class instead? The HttpWebRequest has a CookieContainer property that you can assign a CookieContainer object. This object can be re-used between requests, so I think it should do what you are after.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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