0

I am trying to print a web page at the default printer on the web server. I found the holy grail and it works but prints the login page not the target page, which makes sense because the controller requires auth using the asp.net membership with stock setup. I found this writeup where it is mentioned that you can use the dom interfaces if using forms auth (think that's me) but I'm not sure how to do that. It sounds like that would let the browser hit the login page and post the username/password back to finally hit the target page? Any insight on the best way to proceed would be very helpful, I would not have imagined it would be this involved to print a page that is already rendered (although printing server side it does kinda make sense). Thanks!

Edit: This works: (apparently cookie is the one thing you cannot set in the browser.Navigate method call)

            HttpCookie cookie = Request.Cookies[".ASPXAUTH"];

            InternetSetCookie(htmlPath, ".ASPXAUTH", cookie.Value);

            browser.Navigate(htmlPath);
            while (browser.ReadyState != WebBrowserReadyState.Complete)
                Application.DoEvents();

            dynamic ie = browser.ActiveXInstance;
            ie.ExecWB(OLECMDID_PRINT, OLECMDEXECOPT_DONTPROMPTUSER, PRINT_WAITFORCOMPLETION);

and separately:

            [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
            static extern bool InternetSetCookie(string lpszUrl, string lpszCookieName, string lpszCookieData);

This could be further improved using your code to get the forms cookie specifically instead of by name as my code.

Community
  • 1
  • 1
Vince Bray
  • 53
  • 2
  • 8

1 Answers1

0

The WebBrowser control has an overload method of the Navigate method which allows you to pass additional HTTP headers to the request. In the last argument you could pass the cookie header like this:

browser.Navigate(htmlPath, null, null, "Cookie: authCookie=value" + Environment.NewLine);

where obviously you need to replace authCookie with the name of the authentication cookie your web site expects and value with the value taken from the request cookie.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thanks! I should have looked there. I am close I think but still getting login, see my edit. – Vince Bray Jan 21 '11 at 16:39
  • have tried a variety of things including adding both cookies to the string BUT when I look at my Locals the browser document cookie is still null. any idea what is missing? Thanks – Vince Bray Jan 21 '11 at 20:06
  • @Vince, why are you using the sessionState section to read the cookie name? We are talking about authentication here. Not session. That's not the same thing. Do this instead: `Request.Cookies[FormsAuthentication.FormsCookieName]`. – Darin Dimitrov Jan 21 '11 at 20:16