Wei Ma
Wei Ma

Reputation: 3155

Generate http post request from controller

Forgive me if this is a stupid question. I am not very experienced with Web programming. I am implementing the payment component of my .net mvc application. The component interacts with an external payment service. The payment service accepts http post request in the following form

http://somepaymentservice.com/pay.do?MerchantID=xxx&Price=xxx&otherparameters

I know this is dead easy to do by adding a form in View. However, I do not want my views to deal with third party parameters. I would like my view to submit information to my controller, then controller generates the required url and then send out the request. Following is the pseudo code.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult PayForOrder(OrderForm order)
{
    var url = _paymentService.GetUrlFromOrder(order);
    SendPostRequest(url);
    return View("FinishedPayment");
}  

Is it possible to do so? Does c# have built-in library to generate http request? Thanks in advance.

Upvotes: 10

Views: 36463

Answers (3)

Mathias F
Mathias F

Reputation: 15901

It realy makes a difference if ASP.NET makes a request or the the client makes a request. If the documentation of the the provider says that you should use a form with the given action that has to be submited by the client browser then this might be necessary.

In lots of cases the user (the client) posts some values to the provider, enters some data at the providers site and then gets redirected to your site again. You can not do this applicationflow on the serverside.

Upvotes: 2

user208209
user208209

Reputation:

There certainly is a built in library to generate http requests. Below are two helpful functions that I quickly converted from VB.NET to C#. The first method performs a post the second performs a get. I hope you find them useful.

You'll want to make sure to import the System.Net namespace.

public static HttpWebResponse SendPostRequest(string data, string url) 
{

    //Data parameter Example
    //string data = "name=" + value

    HttpWebRequest httpRequest = HttpWebRequest.Create(url);
    httpRequest.Method = "POST";
    httpRequest.ContentType = "application/x-www-form-urlencoded";
    httpRequest.ContentLength = data.Length;

    var streamWriter = new StreamWriter(httpRequest.GetRequestStream());
    streamWriter.Write(data);
    streamWriter.Close();

    return httpRequest.GetResponse();
}

public static HttpWebResponse SendGetRequest(string url) 
{

    HttpWebRequest httpRequest = HttpWebRequest.Create(url);
    httpRequest.Method = "GET";

    return httpRequest.GetResponse();
}

Upvotes: 6

Andy Gaskell
Andy Gaskell

Reputation: 31761

You'll want to use the HttpWebRequest class. Be sure to set the Method property to post - here's an example.

Upvotes: 8

Related Questions