How can I load a webpage into an iframe, using ASP

2019-04-12 14:07发布

问题:

I have an external webpage that I need to access using a HTTP Post, and include in an iframe. The webpage has an example set of instructions to access the page, listed below, but they assume a Windows Form solution; I am using ASP.NET MVC, instead.

How can I convert this WebBrowser centric solution into something that can successfully post to the external site, and load the results into an iframe?

private WebBrowser wb_inline = null;

private void Submit_Click(object sender, EventArgs e)
{
    string url = "http://www.example.com";
    string setupParameters = "account_token=abc123";

    ServicePointManager.ServerCertificateValidationCallback = 
        (s, cert, chain, ssl) => true;
    ASCIIEncoding encoding = new ASCIIEncoding();
    var postData = setupParameters;

    if (null == wb_inline)
    {
        wb_inline = new WebBrowser(this);
        wb_inline.Location = new System.Drawing.Point(100, 277);
        wb_inline.Size = new System.Drawing.Size(675, 650);
    }
    Controls.Add(wb_inline);
    wb_inline.Visible = true;
    string AdditionalHeaders = "Content-Type: application/json";
    byte[] data = encoding.GetBytes(postData);
    wb_inline.Navigate(payProsUrl, "", data, AdditionalHeaders);
}

Is there a way to do something like this, with a HttpWebResponse (or some other control), and include this in an iframe? I've been trying to adapt this, but without success yet.

回答1:

According to w3schools:

An inline frame is used to embed another document within the current HTML document.

That said, iframe is used to load page contents via a given url and present it to user for interaction. After that you have little control over what user does with the loaded page (he can click links, post forms, etc). You cannot send HTTP request to an iframe as it's just a "window" to show another page and doesn't support complicated scenarios.

One more thing to consider is that the web page you're loading can be protected from embedding into an iframe.

In fact there are some options how you can achieve what you want. For a pure server-side solution using iframe you should do the following:

1.Create an action method, that will do the HTTP POST request to the url you need and fetch the result for presentation:

public ActionResult PostAndShow() 
{
   //do the posting 
   string result = requestStream.ReadToEnd(); //you can have similar code to fetch the server response
   return Content(result);
}

2.In you webpage you will create an iframe that will point to your action PostAndShow and will show the result of your HTTP POST request to third-party server.

<iframe src="@Url.Action("PostAndShow", "My")" width="400" height="300"></iframe>