ASP.NET server-side controls postback to their own page. This makes cases where you want to redirect a user to an external page, but need to post to that page for some reason (for authentication, for instance) a pain.
An HttpWebRequest
works great if you don't want to redirect, and JavaScript is fine in some cases, but can get tricky if you really do need the server-side code to get the data together for the post.
So how do you both post to an external URL and redirect the user to the result from your ASP.NET codebehind code?
Response. Redirect sends an HTTP request to the browser, then the browser sends that request to the web server, then the web server delivers a response to the web browser. For example, suppose you are on the web page "UserRegister. aspx" page and it has a button that redirects you to the "UserDetail.
Here's how I solved this problem today. I started from this article on C# Corner, but found the example - while technically sound - a little incomplete. Everything he said was right, but I needed to hit a few external sites to piece this together to work exactly as I wanted.
It didn't help that the user was not technically submitting a form at all; they were clicking a link to go to our support center, but to log them in an http post had to be made to the support center's site.
This solution involves using HttpContext.Current.Response.Write()
to write the data for the form, then using a bit of Javascript on the <body onload="">
method to submit the form to the proper URL.
When the user clicks on the Support Center link, the following method is called to write the response and redirect the user:
public static void PassthroughAuthentication() { System.Web.HttpContext.Current.Response.Write("<body onload=document.forms[0].submit();window.location=\"Home.aspx\";>"); System.Web.HttpContext.Current.Response.Write("<form name=\"Form\" target=_blank method=post action=\"https://external-url.com/security.asp\">"); System.Web.HttpContext.Current.Response.Write(string.Format("<input type=hidden name=\"cFName\" value=\"{0}\">", "Username")); System.Web.HttpContext.Current.Response.Write("</form>"); System.Web.HttpContext.Current.Response.Write("</body>"); }
The key to this method is in that onload bit of Javascript, which , when the body of the page loads, submits the form and then redirects the user back to my own Home page. The reason for that bit of hoodoo is that I'm launching the external site in a new window, but don't want the user to resubmit the hidden form if they refresh the page. Plus that hidden form pushed the page down a few pixels which got on my nerves.
I'd be very interested in any cleaner ideas anyone has on this one.
Eric Sipple
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With