How Do I Post and then redirect to an external URL from ASP.Net?

By : saalon
Source: Stackoverflow.com
Question!

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?

By : saalon


Answers

I started with this example from CodeProject

Then instead of adding to the page, I borrowed from saalon (above) and did a Response.Write().

By : Kevin


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
By : JnJnBoo


I would do the form post in your code behind using HttpWebRequest class. Here is a good helper class to get your started:

http://geekswithblogs.net/rakker/archive/2006/04/21/76044.aspx

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.

By : sestocker


This video can help you solving your question :)
By: admin