<p>We have the requirement to take a form submission and save some data, then redirect the user to a page offsite, but in redirecting, we need to "submit" a form with POST, not GET.</p>

<p>I was hoping there was an easy way to accomplish this, but I'm starting to think there isn't.  I think I must now create a simple other page, with just the form that I want, redirect to it, populate the form variables, then do a body.onload call to a script that merely calls document.forms[0].submit();</p>

<p>Can anyone tell me if there is an alternative?  We might need to tweak this later in the project, and it might get sort of complicated, so if there was an easy we could do this all non-other page dependent that would be fantastic.</p>

<p>Anyway, thanks for any and all responses.</p>

[{'answer_id': 46611, 'author': 'Jimmy', 'author_id': 4435, 'author_profile': 'https://Stackoverflow.com/users/4435', 'pm_score': 2, 'selected': False, 'text': '<p>PostbackUrl can be set on your asp button to post to a different page.</p>\n\n<p>if you need to do it in codebehind, try Server.Transfer. </p>\n'}, {'answer_id': 46657, 'author': 'Ben Griswold', 'author_id': 4115, 'author_profile': 'https://Stackoverflow.com/users/4115', 'pm_score': 2, 'selected': False, 'text': '<p>I suggest building an HttpWebRequest to programmatically execute your POST and then redirect after reading the Response if applicable.</p>\n'}, {'answer_id': 46700, 'author': 'FlySwat', 'author_id': 1965, 'author_profile': 'https://Stackoverflow.com/users/1965', 'pm_score': 5, 'selected': False, 'text': '<p>HttpWebRequest is used for this.</p>\n\n<p>On postback, create a HttpWebRequest to your third party and post the form data, then once that is done, you can Response.Redirect wherever you want.</p>\n\n<p>You get the added advantage that you don\'t have to name all of your server controls to make the 3rd parties form, you can do this translation when building the POST string.</p>\n\n<pre><code>string url = "3rd Party Url";\n\nStringBuilder postData = new StringBuilder();\n\npostData.Append("first_name=" + HttpUtility.UrlEncode(txtFirstName.Text) + "&amp;");\npostData.Append("last_name=" + HttpUtility.UrlEncode(txtLastName.Text));\n\n//ETC for all Form Elements\n\n// Now to Send Data.\nStreamWriter writer = null;\n\nHttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);\nrequest.Method = "POST";\nrequest.ContentType = "application/x-www-form-urlencoded";                        \nrequest.ContentLength = postData.ToString().Length;\ntry\n{\n    writer = new StreamWriter(request.GetRequestStream());\n    writer.Write(postData.ToString());\n}\nfinally\n{\n    if (writer != null)\n        writer.Close();\n}\n\nResponse.Redirect("NewPage");\n</code></pre>\n\n<p>However, if you need the user to see the response page from this form, your only option is to utilize Server.Transfer, and that may or may not work.</p>\n'}, {'answer_id': 46906, 'author': 'FlySwat', 'author_id': 1965, 'author_profile': 'https://Stackoverflow.com/users/1965', 'pm_score': 2, 'selected': False, 'text': '<p>@Matt,</p>\n\n<p>You can still use the HttpWebRequest, then direct the response you receive to the actual outputstream response, this would serve the response back to the user. The only issue is that any relative urls would be broken.</p>\n\n<p>Still, that may work.</p>\n'}, {'answer_id': 47670, 'author': 'Andrei Rînea', 'author_id': 1796, 'author_profile': 'https://Stackoverflow.com/users/1796', 'pm_score': 2, 'selected': False, 'text': '<p>Here\'s what I\'d do :</p>\n\n<p>Put the data in a standard form (with no runat="server" attribute) and set the action of the form to post to the target off-site page.\nBefore submitting I would submit the data to my server <strong>using an XmlHttpRequest</strong> and analyze the response. If the response means you should go ahead with the offsite POSTing then I (the JavaScript) would proceed with the post otherwise I would redirect to a page on my site</p>\n'}, {'answer_id': 47735, 'author': 'tghw', 'author_id': 2363, 'author_profile': 'https://Stackoverflow.com/users/2363', 'pm_score': 9, 'selected': True, 'text': '<p>Doing this requires understanding how HTTP redirects work.  When you use <code>Response.Redirect()</code>, you send a response (to the browser that made the request) with <a href="http://en.wikipedia.org/wiki/HTTP_302" rel="noreferrer">HTTP Status Code 302</a>, which tells the browser where to go next.  By definition, the browser will make that via a <code>GET</code> request, even if the original request was a <code>POST</code>.</p>\n\n<p>Another option is to use <a href="http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#3xx_Redirection" rel="noreferrer">HTTP Status Code 307</a>, which specifies that the browser should make the redirect request in the same way as the original request, but to prompt the user with a security warning.  To do that, you would write something like this:</p>\n\n<pre><code>public void PageLoad(object sender, EventArgs e)\n{\n    // Process the post on your side   \n\n    Response.Status = "307 Temporary Redirect";\n    Response.AddHeader("Location", "http://example.com/page/to/post.to");\n}\n</code></pre>\n\n<p>Unfortunately, this won\'t always work.  <a href="http://ilia.ws/archives/152-Cross-Domain-POST-Redirection.html" rel="noreferrer">Different browsers implement this differently</a>, since it is not a common status code.</p>\n\n<blockquote>\n  <p>Alas, unlike the Opera and FireFox developers, the IE developers have never read the spec, and even the latest, most secure IE7 will redirect the POST request from domain A to domain B without any warnings or confirmation dialogs! Safari also acts in an interesting manner, while it does not raise a confirmation dialog and performs the redirect, it throws away the POST data, <strong>effectively changing 307 redirect into the more common 302.</strong></p>\n</blockquote>\n\n<p>So, as far as I know, the only way to implement something like this would be to use Javascript.  There are two options I can think of off the top of my head:</p>\n\n<ol>\n<li>Create the form and have its <code>action</code> attribute point to the third-party server.  Then, add a click event to the submit button that first executes an AJAX request to your server with the data, and then allows the form to be submitted to the third-party server.</li>\n<li>Create the form to post to your server.  When the form is submitted, show the user a page that has a form in it with all of the data you want to pass on, all in hidden inputs.  Just show a message like "Redirecting...".  Then, add a javascript event to the page that submits the form to the third-party server.</li>\n</ol>\n\n<p>Of the two, I would choose the second, for two reasons.  First, it is more reliable than the first because Javascript is not required for it to work; for those who don\'t have it enabled, you can always make the submit button for the hidden form visible, and instruct them to press it if it takes more than 5 seconds.  Second, you can decide what data gets transmitted to the third-party server; if you use just process the form as it goes by, you will be passing along all of the post data, which is not always what you want.  Same for the 307 solution, assuming it worked for all of your users.</p>\n\n<p>Hope this helps!</p>\n'}, {'answer_id': 47832, 'author': 'FlySwat', 'author_id': 1965, 'author_profile': 'https://Stackoverflow.com/users/1965', 'pm_score': 2, 'selected': False, 'text': '<blockquote>\n  <p>In PHP, you can send POST data with cURL. Is there something comparable for .NET?</p>\n</blockquote>\n\n<p>Yes, HttpWebRequest, see my post below.</p>\n'}, {'answer_id': 50809, 'author': 'erickson', 'author_id': 3474, 'author_profile': 'https://Stackoverflow.com/users/3474', 'pm_score': 2, 'selected': False, 'text': '<p>The GET (and HEAD) method should never be used to do anything that has side-effects. A side-effect might be updating the state of a web application, or it might be charging your credit card. If an action has side-effects another method (POST) should be used instead.</p>\n\n<p>So, a user (or their browser) shouldn\'t be held accountable for something done by a GET. If some harmful or expensive side-effect occurred as the result of a GET, that would be the fault of the web application, not the user. According to the spec, a user agent <strong>must not</strong> automatically follow a redirect unless it is a response to a GET or HEAD request.</p>\n\n<p>Of course, a lot of GET requests do have some side-effects, even if it\'s just appending to a log file. The important thing is that the application, not the user, should be held responsible for those effects.</p>\n\n<p>The relevant sections of the HTTP spec are <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html" rel="nofollow noreferrer">9.1.1 and 9.1.2</a>, and <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3" rel="nofollow noreferrer">10.3</a>.</p>\n'}, {'answer_id': 1353717, 'author': 'John Leidegren', 'author_id': 58961, 'author_profile': 'https://Stackoverflow.com/users/58961', 'pm_score': 1, 'selected': False, 'text': '<p>Typically, all you\'ll ever need is to carry some state between these two requests. There\'s actually a really funky way to do this which doesn\'t rely on JavaScript (think &lt;noscript/>).</p>\n\n<pre><code>Set-Cookie: name=value; Max-Age=120; Path=/redirect.html\n</code></pre>\n\n<p>With that cookie there, you can in the following request to /redirect.html retrieve the name=value info, you can store any kind of information in this name/value pair string, up to say 4K of data (typical cookie limit). Of course you should avoid this and store status codes and flag bits instead.</p>\n\n<p>Upon receiving this request you in return respond with a delete request for that status code.</p>\n\n<pre><code>Set-Cookie: name=value; Max-Age=0; Path=/redirect.html\n</code></pre>\n\n<p>My HTTP is a bit rusty I\'ve been going trough RFC2109 and RFC2965 to figure how reliable this really is, preferably I would want the cookie to round trip exactly once but that doesn\'t seem to be possible, also, <em>third-party cookies might be a problem for you if you are relocating to another domain. This is still possible but not as painless as when you\'re doing stuff within your own domain.</em></p>\n\n<p>The problem here is concurrency, if a power user is using multiple tabs and manages to interleave a couple of requests belonging to the same session (this is very unlikely, but not impossible) this may lead to inconsistencies in your application.</p>\n\n<p>It\'s the &lt;noscript/> way of doing HTTP round trips without meaningless URLs and JavaScript</p>\n\n<p>I provide this code as a prof of concept: If this code is run in a context that you are not familiar with I think you can work out what part is what.</p>\n\n<p>The idea is that you call Relocate with some state when you redirect, and the URL which you relocated calls GetState to get the data (if any).</p>\n\n<pre><code>const string StateCookieName = "state";\n\nstatic int StateCookieID;\n\nprotected void Relocate(string url, object state)\n{\n    var key = "__" + StateCookieName + Interlocked\n        .Add(ref StateCookieID, 1).ToInvariantString();\n\n    var absoluteExpiration = DateTime.Now\n        .Add(new TimeSpan(120 * TimeSpan.TicksPerSecond));\n\n    Context.Cache.Insert(key, state, null, absoluteExpiration,\n        Cache.NoSlidingExpiration);\n\n    var path = Context.Response.ApplyAppPathModifier(url);\n\n    Context.Response.Cookies\n        .Add(new HttpCookie(StateCookieName, key)\n        {\n            Path = path,\n            Expires = absoluteExpiration\n        });\n\n    Context.Response.Redirect(path, false);\n}\n\nprotected TData GetState&lt;TData&gt;()\n    where TData : class\n{\n    var cookie = Context.Request.Cookies[StateCookieName];\n    if (cookie != null)\n    {\n        var key = cookie.Value;\n        if (key.IsNonEmpty())\n        {\n            var obj = Context.Cache.Remove(key);\n\n            Context.Response.Cookies\n                .Add(new HttpCookie(StateCookieName)\n                { \n                    Path = cookie.Path, \n                    Expires = new DateTime(1970, 1, 1) \n                });\n\n            return obj as TData;\n        }\n    }\n    return null;\n}\n</code></pre>\n'}, {'answer_id': 2802848, 'author': 'Pavlo Neiman', 'author_id': 164001, 'author_profile': 'https://Stackoverflow.com/users/164001', 'pm_score': 7, 'selected': False, 'text': '<p>You can use this aproach:</p>\n\n<pre><code>Response.Clear();\n\nStringBuilder sb = new StringBuilder();\nsb.Append("&lt;html&gt;");\nsb.AppendFormat(@"&lt;body onload=\'document.forms[""form""].submit()\'&gt;");\nsb.AppendFormat("&lt;form name=\'form\' action=\'{0}\' method=\'post\'&gt;",postbackUrl);\nsb.AppendFormat("&lt;input type=\'hidden\' name=\'id\' value=\'{0}\'&gt;", id);\n// Other params go here\nsb.Append("&lt;/form&gt;");\nsb.Append("&lt;/body&gt;");\nsb.Append("&lt;/html&gt;");\n\nResponse.Write(sb.ToString());\n\nResponse.End();\n</code></pre>\n\n<p>As result right after client will get all html from server the event <strong>onload</strong> take place that triggers form submit and post all data to defined postbackUrl.</p>\n'}, {'answer_id': 2825011, 'author': 'Mike K', 'author_id': 45606, 'author_profile': 'https://Stackoverflow.com/users/45606', 'pm_score': 3, 'selected': False, 'text': '<p>Something new in ASP.Net 3.5 is this "PostBackUrl" property of ASP buttons.  You can set it to the address of the page you want to post directly to, and when that button is clicked, instead of posting back to the same page like normal, it instead posts to the page you\'ve indicated.  Handy. Be sure UseSubmitBehavior is also set to TRUE.</p>\n'}, {'answer_id': 12175053, 'author': 'ZooZ', 'author_id': 772930, 'author_profile': 'https://Stackoverflow.com/users/772930', 'pm_score': 3, 'selected': False, 'text': '<p>This should make life much easier.\nYou can simply use Response.RedirectWithData(...) method in your web application easily.</p>\n\n<pre><code>Imports System.Web\nImports System.Runtime.CompilerServices\n\nModule WebExtensions\n\n    &lt;Extension()&gt; _\n    Public Sub RedirectWithData(ByRef aThis As HttpResponse, ByVal aDestination As String, _\n                                ByVal aData As NameValueCollection)\n        aThis.Clear()\n        Dim sb As StringBuilder = New StringBuilder()\n\n        sb.Append("&lt;html&gt;")\n        sb.AppendFormat("&lt;body onload=\'document.forms[""form""].submit()\'&gt;")\n        sb.AppendFormat("&lt;form name=\'form\' action=\'{0}\' method=\'post\'&gt;", aDestination)\n\n        For Each key As String In aData\n            sb.AppendFormat("&lt;input type=\'hidden\' name=\'{0}\' value=\'{1}\' /&gt;", key, aData(key))\n        Next\n\n        sb.Append("&lt;/form&gt;")\n        sb.Append("&lt;/body&gt;")\n        sb.Append("&lt;/html&gt;")\n\n        aThis.Write(sb.ToString())\n\n        aThis.End()\n    End Sub\n\nEnd Module\n</code></pre>\n'}, {'answer_id': 19598053, 'author': 'jacob', 'author_id': 1784298, 'author_profile': 'https://Stackoverflow.com/users/1784298', 'pm_score': 3, 'selected': False, 'text': '<p>Thought it might interesting to share that heroku does this with it\'s SSO to Add-on providers</p>\n\n<p>An example of how it works can be seen in the source to the "kensa" tool:</p>\n\n<p><a href="https://github.com/heroku/kensa/blob/d4a56d50dcbebc2d26a4950081acda988937ee10/lib/heroku/kensa/post_proxy.rb" rel="noreferrer">https://github.com/heroku/kensa/blob/d4a56d50dcbebc2d26a4950081acda988937ee10/lib/heroku/kensa/post_proxy.rb</a></p>\n\n<p>And can be seen in practice if you turn of javascript.  Example page source:</p>\n\n<pre><code>&lt;!DOCTYPE HTML&gt;\n&lt;html&gt;\n  &lt;head&gt;\n    &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt;\n    &lt;title&gt;Heroku Add-ons SSO&lt;/title&gt;\n  &lt;/head&gt;\n\n  &lt;body&gt;\n    &lt;form method="POST" action="https://XXXXXXXX/sso/login"&gt;\n\n        &lt;input type="hidden" name="email" value="XXXXXXXX" /&gt;\n\n        &lt;input type="hidden" name="app" value="XXXXXXXXXX" /&gt;\n\n        &lt;input type="hidden" name="id" value="XXXXXXXX" /&gt;\n\n        &lt;input type="hidden" name="timestamp" value="1382728968" /&gt;\n\n        &lt;input type="hidden" name="token" value="XXXXXXX" /&gt;\n\n        &lt;input type="hidden" name="nav-data" value="XXXXXXXXX" /&gt;\n\n    &lt;/form&gt;\n\n    &lt;script type="text/javascript"&gt;\n      document.forms[0].submit();\n    &lt;/script&gt;\n  &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n'}, {'answer_id': 54929640, 'author': 'Zar Shardan', 'author_id': 913845, 'author_profile': 'https://Stackoverflow.com/users/913845', 'pm_score': 1, 'selected': False, 'text': '<p>Copy-pasteable code based on <a href="https://stackoverflow.com/a/2802848/913845">Pavlo Neyman\'s method</a></p>\n\n<p>RedirectPost(string url, T bodyPayload) and GetPostData() are for those who just want to dump some strongly typed data in the source page and fetch it back in the target one.\nThe data must be serializeable by NewtonSoft Json.NET and you need to reference the library of course.</p>\n\n<p>Just copy-paste into your page(s) or better yet base class for your pages and use it anywhere in you application. </p>\n\n<p>My heart goes out to all of you who still have to use Web Forms in 2019 for whatever reason.</p>\n\n<pre><code>        protected void RedirectPost(string url, IEnumerable&lt;KeyValuePair&lt;string,string&gt;&gt; fields)\n        {\n            Response.Clear();\n\n            const string template =\n@"&lt;html&gt;\n&lt;body onload=\'document.forms[""form""].submit()\'&gt;\n&lt;form name=\'form\' action=\'{0}\' method=\'post\'&gt;\n{1}\n&lt;/form&gt;\n&lt;/body&gt;\n&lt;/html&gt;";\n\n            var fieldsSection = string.Join(\n                    Environment.NewLine,\n                    fields.Select(x =&gt; $"&lt;input type=\'hidden\' name=\'{HttpUtility.UrlEncode(x.Key)}\' value=\'{HttpUtility.UrlEncode(x.Value)}\'&gt;")\n                );\n\n            var html = string.Format(template, HttpUtility.UrlEncode(url), fieldsSection);\n\n            Response.Write(html);\n\n            Response.End();\n        }\n\n        private const string JsonDataFieldName = "_jsonData";\n\n        protected void RedirectPost&lt;T&gt;(string url, T bodyPayload)\n        {\n            var json = JsonConvert.SerializeObject(bodyPayload, Formatting.Indented);\n            //explicit type declaration to prevent recursion\n            IEnumerable&lt;KeyValuePair&lt;string, string&gt;&gt; postFields = new List&lt;KeyValuePair&lt;string, string&gt;&gt;()\n                {new KeyValuePair&lt;string, string&gt;(JsonDataFieldName, json)};\n\n            RedirectPost(url, postFields);\n\n        }\n\n        protected T GetPostData&lt;T&gt;() where T: class \n        {\n            var urlEncodedFieldData = Request.Params[JsonDataFieldName];\n            if (string.IsNullOrEmpty(urlEncodedFieldData))\n            {\n                return null;// default(T);\n            }\n\n            var fieldData = HttpUtility.UrlDecode(urlEncodedFieldData);\n\n            var result = JsonConvert.DeserializeObject&lt;T&gt;(fieldData);\n            return result;\n        }\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/46582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/232/']