I want to go to a page in a web application from a desktop application. “No problem,” I heard you say, “Just launch the default browser with the correct URL.” However, the web application uses ASP.NET Forms Authentication, and users do not want to see the login page because they have already authenticated with the same credentials in the desktop application.
It sounds simple enough, all I have to do is release the HTTP POST from the desktop application, which will result in a postback from the login page of the web application. Then the web application will set its authentication ticket and session state cookies, return them to me, and I will save them in the IE cookie store. Then I can go to the desired page, and the web application will consider that it has already been completed.
I have a working code that builds an HTTP POST, sends it and receives a valid response containing the correct cookies. However, I cannot figure out how to write them to the IE cookie store. Can someone point me in the right direction?
Code example:
var requestUrl = Properties.Settings.Default.WebsiteLoginPageUrl;
var requestEncoding = Encoding.GetEncoding(1252);
var requestText = string.Format(
"__VIEWSTATE={2}&__EVENTTARGET={3}&__EVENTARGUMENT={4}&__EVENTVALIDATION={5}&userNameText={0}&passwordText={1}&submitButton=Log+In",
HttpUtility.UrlEncode(Properties.Settings.Default.UserName),
HttpUtility.UrlEncode(Properties.Settings.Default.Password),
Properties.Settings.Default.FakeViewState,
Properties.Settings.Default.FakeEventTarget,
Properties.Settings.Default.FakeEventArgument,
Properties.Settings.Default.FakeEventValidation);
var request = (HttpWebRequest) WebRequest.Create(requestUrl);
request.Method = "POST";
request.Accept = "*/*";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = requestEncoding.GetByteCount(requestText);
request.Headers.Add(HttpRequestHeader.CacheControl, "no-cache");
request.AllowAutoRedirect = false;
request.KeepAlive = false;
request.CookieContainer = new CookieContainer();
using(var writer = new StreamWriter(request.GetRequestStream(), requestEncoding)) {
writer.Write(requestText);
}
var response = (HttpWebResponse) request.GetResponse();
Process.Start(new ProcessStartInfo {
FileName = Properties.Settings.Default.WebsiteTargetPageUrl,
UseShellExecute = true,
});