How to perform an HTTP POST and redirect the user

2019-08-25 10:05发布

问题:

So as the title suggest how does one perform an HTTP POST to an external website while also redirecting the user there? I am looking for something similar to this:

Redirect("MyWebsite.com", HttpAction.POST, new RedirectData(new { item = "itemValue"}));

It has to be done in ASP.NET mvc.

EDIT

This behaviour is necessary to implement authentication on an external website. The algorithm for the authentication:

  1. User navigates to the webpage that requires him to be identified.
  2. The webpage calls the web service of the authentication website and initializes authentication.
  3. Initialization returns GUID that has to be posted to the given URL (let's say it is "MyWebsite.com").
  4. The user is supposed to be redirected to the URL that data was posted to.

So far I've managed to come up with this:

string url = "MyWebsite.com";
NameValueCollection formData = new NameValueCollection();
formData["ticket"] = Ticket.ticket;
WebClient webClient = new WebClient();
byte[] responseBytes = webClient.UploadValues(url, "POST", formData);

Response.BinaryWrite(responseBytes);
Response.Redirect("MyWebsite.com", true);

The response I get is the HTML of the website I am supposed to be redirected to and the question is - what now? How do I tell the browser to display HTML that I got via the response? If I simply redirect to "MyWebSite.com" it would execute a GET action, which is not what I am looking for. Doing binary write of the response accomplishes nothing - it just writes the response of the POST action to the action I am currently executing - there is no redirect to "MyWebSite.com".

回答1:

If you want to post and redirect to an external site, then you should just make your form's action go to that URL directly. There's no reason to handle anything on your side. However, unless you control the external site or have some sort of arrangement to be able to do this, it very likely won't work. Just about every platform implements some sort of CSRF protection to prevent exactly this type of thing.



回答2:

.NET Supports the following -

   using (var client = new WebClient())
    {
        client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-      urlencoded";
        var data = new Person 
        { 
              Name = "Glitch100"
        }
        var result = client.UploadString("http://www.website.com/page/", "POST", data);
        Console.WriteLine(result);
    }

WebClient or HttpWebRequest can be used on the server side to POST data.

Curious - what is the reason for wanting to do this?

Links:

http://msdn.microsoft.com/en-us/library/system.net.webclient(v=vs.110).aspx

POST string to ASP.NET Web Api application - returns null

how to POST data to external URL in MVC4 using server side