Веб-клиент Cookies не работают с другими URL - PullRequest
0 голосов
/ 22 декабря 2018

На данный момент это мой код:

using System;
using System.Collections.Specialized;
using System.Net;
using System.Text;

namespace ConsoleApp1
{
    class Program
    {
        public class CookieWebClient : WebClient
        {
            public CookieContainer CookieContainer { get; private set; }

            /// <summary>
            /// This will instanciate an internal CookieContainer.
            /// </summary>
            public CookieWebClient()
            {
                this.CookieContainer = new CookieContainer();
            }

            /// <summary>
            /// Use this if you want to control the CookieContainer outside this class.
            /// </summary>
            public CookieWebClient(CookieContainer cookieContainer)
            {
                this.CookieContainer = cookieContainer;
            }

            protected override WebRequest GetWebRequest(Uri address)
            {
                var request = base.GetWebRequest(address) as HttpWebRequest;
                if (request == null) return base.GetWebRequest(address);
                request.CookieContainer = CookieContainer;
                return request;
            }
        }

        static void Main(string[] args)
        {
            using (var client = new CookieWebClient())
            {
                var loginData = new NameValueCollection
                {
                    { "username", "USER" },
                    { "password", "PASS" }
                };

                // Login into the website (at this point the Cookie Container will do the rest of the job for us, and save the cookie for the next calls)
                byte[] responsebytes = client.UploadValues("https://website.com/api/Login.php", "POST", loginData);
                string responsebody = Encoding.UTF8.GetString(responsebytes);
                Console.WriteLine(responsebody);

                // Call authenticated resources
                byte[] responsebytes2 = client.DownloadData("https://website.com/forum/user.php");
                string responsebody2 = Encoding.UTF8.GetString(responsebytes2);
                Console.WriteLine(responsebody2);
            }
        }
    }
}

Входная часть работает отлично, но как только я пытаюсь прочитать данные со второго URL, это показывает, что я на самом деле не вошел в систему. Не знаю, почему этоне работает в C #.Я не очень много знаю, когда речь заходит о C #, поэтому я впервые создал тест, похожий на приведенный выше код на Java, в котором используется

CookieManager cm = new CookieManager();
            CookieHandler.setDefault(cm);

До сих пор он прекрасно работал в Java.Я перепробовал несколько классов и решений, но до сих пор не нашел ничего, что работает.

...