Is there any way to pass login information to read a website in C#

i want to read a website in C# using this:

        WebRequest myWebRequest = WebRequest.Create("http://www.myurl.com/test.aspx");
        WebResponse myWebResponse = myWebRequest.GetResponse();
        Stream ReceiveStream = myWebResponse.GetResponseStream();
        Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
        StreamReader readStream = new StreamReader(ReceiveStream, encode);
        string strResponse = readStream.ReadToEnd();

the issue is that they now have authentication on the page so i get the login prompt when i go to the website and have to type in user name and login.

my code now returns the error:

The remote server returned an error: (401) Unauthorized.

i tried adding this:

myWebRequest.Credentials = new NetworkCredential("[username]", "[pwd]");

and this:

ServicePointManager.ServerCertificateValidationCallback += delegate { return true; }; 

but still got the same error:

Is there anyway to pass those credentials in the WebRequest code above?

Answers


If the website is using HTTP basic authentication (a browser-generated login dialog), you can set the HttpWebRequest's Credentials property to a NetworkCredential instance.

If the website uses forms authentication (an HTML-based login form; this is more common), you'll need to make a separate request to login to the site and share a CookieContainer across the requests to preserve the login. You can use Fiddler to see what the login request should look like.


Need Your Help

Methods adding Excel-like features to R plots?

r graphics

I've been poking around with R graphical parameters trying to make my plots look a little more professional (e.g., las=1, bty="n" usually help). Started playing with tikzDevice, which was a huge

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.