How do I post and then redirect to an external URL from ASP_Net?
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?
6 Answers
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.
I started with this example from CodeProject.
Then instead of adding to the page, I borrowed from saalon (above) and did a Response.Write()
.
I would do the form post in your code behind using HttpWebRequest class. Here is a good helper class to get your started.
From there, you can just do a Response.Redirect
, or perhaps you need to vary your action based on the outcome of the post (if there was an error, display it to the user or whatever). I think you already had the answer in your question to be honest - sounds like you think it is a post OR redirect when in reality you can do them both from your code behind.
I have done this by rendering a form that auto-posts (using JavaScript) to the desired remote URL - gather whatever information you need for the post in the web form's postback and then build the HTML for the remote-posting form and render it back to the client.
I built a utility class for this that contains the remote URL and a collection of name/value pairs for the form.
Cross-page posting will work if you own both of the pages involved, but not if you need to post to another site (PayPal, for example).
If you're using ASP_NET 2_0, you can do this with cross-page posting.
Edit: I missed the fact that you're asking about an external page. For that I think you'd need to have your ASP_NET page gen up an HTML form whose action is set to the remote URL
and method is set to POST
. (Using cross-page posting, this could even be a different page with no UI, only hidden form elements.) Then add a bit of javascript to submit the form as soon as the postback result was received on the client.
I needed to open in the same window, dealing with possible frame issues from the original page, then redirecting to an external site in code behind:
Private Sub ExternalRedirector(ByVal externalUrl As String)
Dim clientRedirectName As String = "ClientExternalRedirect"
Dim externalRedirectJS As New StringBuilder()
If Not String.IsNullOrEmpty(externalUrl) Then
If Not Page.ClientScript.IsStartupScriptRegistered(clientRedirectName) Then
externalRedirectJS.Append("function CheckWindow() {")
externalRedirectJS.Append(" if (window.top != window) {")
externalRedirectJS.Append(" window.top.location = '")
externalRedirectJS.Append(externalUrl)
externalRedirectJS.Append("';")
externalRedirectJS.Append(" return false;")
externalRedirectJS.Append(" }")
externalRedirectJS.Append(" else {")
externalRedirectJS.Append(" window.location = '")
externalRedirectJS.Append(externalUrl)
externalRedirectJS.Append("';")
externalRedirectJS.Append(" }")
externalRedirectJS.Append("}")
externalRedirectJS.Append("CheckWindow();")
Page.ClientScript.RegisterStartupScript(Page.GetType(), clientRedirectName, externalRedirectJS.ToString(), True)
End If
End If
End Sub
I'm working on a website that will switch to a new style on a set date. The site's built-in semantic HTML and CSS, so the change should just require a CSS reference change. I'm working with a designer who will need to be able to see how it's looking, as well as a client who will need to be able to review content updates in the current look as well as design progress on the new look. I'm planning to use a magic querystring value and/or a javascript link in the footer which writes out a cookie to select the new CSS page. We're working in ASP_NET 3.5. Any recommendations? I should mention that we're using IE Conditional Comments for IE8, 7, and 6 support. I may create a function that does a replacement: <link href="Style/<% GetCssRoot() %>.css" rel="stylesheet" type="text/css" /> <!--[if lte IE 8]> <link type="text/css" href="Style/<% GetCssRoot() %>…
I'm using ColdFusion to populate a template that includes HTML unordered lists ( <ul> s). Most of these aren't that long, but a few have ridiculously long lengths and could really stand to be in 2-3 columns. Is there an HTML, ColdFusion or perhaps JavaScript (I'm accepting jQuery solutions) way to do this easily? It's not worth some over-complicated heavyweight solution to save some scrolling. Is this jquery plugin of any use to you? Check out the Columnizer jQuery plugin. So I dug up this article from A List Apart CSS Swag: Multi-Column Lists. I ended up using the first solution, it's not the best but the others require either…
How do I keyboard up or down between drop-down options?
I have a custom built ajax [div] based dynamic dropdown. I have an [input] box which; onkeyup , runs an Ajax search which returns results in div s and are drawn back in using innerHTML . These div s all have highlights onmouseover so, a typical successful search yields the following structure (pardon the semi-code): [input] [div id=results] //this gets overwritten contantly by my AJAX function [div id=result1 onmouseover=highlight onclick=input.value=result1]…