简体   繁体   中英

log in to a web page programatically using C#

I want to login to webpage http://abc/mypage/config/login.aspx and fetch html of http://abc/mypage/config/config.aspx page. I have used webrequest and tried but i am always getting login page html.

WebRequest request = WebRequest.Create("http://abc/mypage/config/login.aspx");
request.Method = "POST";

string postData = "usernameTextBox=myUsername&passwordTextBox=myPassword";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();

My header for this request is:

Accept
text/html,application/xhtml+xml,application/xml;q=0.9, / ;q=0.8 Accept-Encoding gzip, deflate Accept-Language en-US,en;q=0.5 Connection keep-alive Cookie
ASP.NET_SessionId=nyifft45s13wni45bw0qer3z Host
192.168.174.16 Referer http://abc/mypage/config/login.aspx User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0

I need to login through this page and get the html of config.aspx page.

Any help will be appreciated.

Thank You.

I guess the website is using Form authentication based on your code and aspx page. Try add a cookiecontainer

    Cookiecontainer cookies = new Cookiecontainer();

   //login request to get authentication cookies.
    WebRequest request = WebRequest.Create("http://abc/mypage/config/login.aspx");
    request.Method = "POST";
    request.cookiecontainer = cookies

    //your rest of the code

  //content request to get what you need
  WebRequest request = WebRequest.Create("http://abc/mypage/config/config.aspx");
    request.Method = "POST";
    request.cookiecontainer = cookies

   //same as before

you should get what you need back, if the authentication is through cookies.

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