title: Login to other web site from ASP .NET MVC 5 programmatically with Username & Password
body: <p>I am working on ASP .Net MVC 5 and want to login programmatically to other web site (server side) and access its source page after log in. I did POST request as shown in below code with "OK" response but the page source always showing that I need to login.</p>
  
  <pre><code>//Code on controller
  private static string LoginOn(string url, string email, string password)
  {
      try
      {
           var http = WebRequest.Create(url) as HttpWebRequest;
           http.KeepAlive = true;
           http.Method = "POST";
           http.ContentType = "application/x-www-form-urlencoded";
           var dataBytes = Encoding.UTF8.GetBytes($"vb_login_username={email}&amp;vb_login_password={password}");
           http.ContentLength = dataBytes.Length;
  
           //http.AllowAutoRedirect = false;
           using (var postStream = http.GetRequestStream())
           {
              postStream.Write(dataBytes, 0, dataBytes.Length);
           }
           var httpResponse = http.GetResponse() as HttpWebResponse;
           var source = string.Empty;
           using (StreamReader sr = new StreamReader(httpResponse.GetResponseStream()))
           {
              source = sr.ReadToEnd(); //I debug source here
           }
           return httpResponse?.ResponseUri.ToString();
  
           //http = WebRequest.Create(httpResponse?.ResponseUri.ToString()) as HttpWebRequest;
           //http.CookieContainer = new CookieContainer();
           //http.CookieContainer.Add(httpResponse.Cookies);
           //HttpWebResponse httpResponse2 = http.GetResponse() as HttpWebResponse;
           //using (StreamReader sr = new StreamReader(httpResponse2.GetResponseStream()))
           //{
           //   source = sr.ReadToEnd();
           //}
           //return httpResponse2?.ResponseUri.ToString();
      }
      catch (Exception e)
      {
         Log(e);
      }
      return null;
  }
  </code></pre>