简体   繁体   中英

C# WebRequest POST returns Html page - how to display it in browser

I'm working with the SagePay payment gateway.

On a checkout button click I'm using the method below to postData (contains the transaction data) to SagePay who then return the result in the form of a html page.

public string SendRequest(string url, string postData)
{
    var uri = new Uri(url);
    var request = WebRequest.Create(uri);
    var encoding = new UTF8Encoding();
    var requestData = encoding.GetBytes(postData);

    request.ContentType = "application/x-www-form-urlencoded";
    request.Method = "POST";
    request.Timeout = (300 * 1000); //TODO: Move timeout to config
    request.ContentLength = requestData.Length;

    using (var stream = request.GetRequestStream())
    {
        stream.Write(requestData, 0, requestData.Length);
    }

    var response = request.GetResponse();

    string result;

    using (var reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
    {
        result = reader.ReadToEnd();
    }

    return result;
}

How do I show this returned html in the users browser window as this would be where they enter their credit card info?

Assuming this is a Forms application, why not use a System.Windows.Forms.WebBrowser control? It has a nifty property, DocumentStream . Hooking it up to a stream is as simple as:

 
 
 
  
   var webRequest = WebRequest.Create("http://www.google.com"); var response = webRequest.GetResponse(); webBrowser1.DocumentStream = response.GetResponseStream();
 
  

Maybe rewriting the doc with fully qualified URLs might help, although I suspect a payment gateway might get funny about referer (sic).

        string responseString;
        var webRequest = WebRequest.Create("http://www.google.com");
        using (var response = webRequest.GetResponse())
        using (var sr = new StreamReader(response.GetResponseStream()))
        {
            responseString = sr.ReadToEnd();
        }
        //consider rewriting some URLs in the response so they are fully qualified
        //in method below.
        //responseString=ProcessResponseString();
        //squirt response back to user

if you're working in a Web Application(ASP.NET),you can make this:

Markup:

 <div id="HTMLResponse" runat="server"></div>

ASP.NET:

HTMLResponse.InnerHtml = SendRequest(...); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM