Logging into a Web site using WebRequest

1

I need to log into a site using asp.net web forms. I'm doing it this way. How could I redirect to the page after logging in?

        protected void Button1_Click(object sender, EventArgs e)
        {
            var loginAddress = "http://sportone.sisguardiao.com.br/";
            var loginData = new NameValueCollection
                    {
                      { "LOGIN", "abfg" },
                      { "SENHA", "123" }
                    };
            Login(loginAddress, loginData);

        }

        public void Login(string loginPageAddress, NameValueCollection loginData)
        {
            CookieContainer container;

            var request = (HttpWebRequest)WebRequest.Create(loginPageAddress);

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            var buffer = Encoding.ASCII.GetBytes(loginData.ToString());
            request.ContentLength = buffer.Length;
            var requestStream = request.GetRequestStream();
            requestStream.Write(buffer, 0, buffer.Length);
            requestStream.Close();

            container = request.CookieContainer = new CookieContainer();

            var response = request.GetResponse();
            response.Close();

        }
    
asked by anonymous 19.09.2016 / 20:00

1 answer

1

Make Login return bool :

    public bool Login(string loginPageAddress, NameValueCollection loginData)
    {
        try 
        {
            CookieContainer container;

            var request = (HttpWebRequest)WebRequest.Create(loginPageAddress);

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            var buffer = Encoding.ASCII.GetBytes(loginData.ToString());
            request.ContentLength = buffer.Length;
            var requestStream = request.GetRequestStream();
            requestStream.Write(buffer, 0, buffer.Length);
            requestStream.Close();

            container = request.CookieContainer = new CookieContainer();

            var response = request.GetResponse();
            response.Close();

            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }

In the button event:

    protected void Button1_Click(object sender, EventArgs e)
    {
        var loginAddress = "http://sportone.sisguardiao.com.br/";
        var loginData = new NameValueCollection
                {
                  { "LOGIN", "abfg" },
                  { "SENHA", "123" }
                };

        if (Login(loginAddress, loginData))
            Server.Transfer("Pagina.aspx", true);
    }

Or, still, if you want to redirect to a fixed address, use, instead of Server.Transfer :

Response.Redirect("http://sportone.sisguardiao.com.br");
    
19.09.2016 / 20:20