使用用户名&amp ;;以编程方式从ASP .NET MVC 5登录到其他网站。密码

时间:2015-11-11 10:39:07

标签: c# asp.net-mvc httpwebrequest

我正在研究ASP .Net MVC 5,并希望以编程方式登录到其他网站(服务器端)并在登录后访问其源页面。我做了POST请求,如下面的代码所示“OK”响应但是页面源始终显示我需要登录。

//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}&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;
}

0 个答案:

没有答案