跨浏览器脚本代理

Cross browser scripting proxy

本文关键字:代理 脚本 浏览器      更新时间:2023-09-26

我正在开发一些客户端Javascript,它在不同的域上使用一些JSON Web服务。 我已经读到某些浏览器不允许跨域脚本,我应该在本地服务器上创建一个代理来提供数据。

有人可以指出我一个简单的例子,说明如何在 ASP.Net 做到这一点吗?

一般来说,代理在您的 Web 服务器上运行(在您的情况下很可能是 IIS ),并将请求"中继"到不同域上的另一台服务器。

下面是在 C# .NET 中实现的一个示例

快速、流式 AJAX 代理

您可以通过使用 JSONP 等技术来避免代理。假设您正在与之交谈的Web服务支持JSONP(例如,Flickr或Twitter都提供JSONP API),或者您可以控制Web服务发回的数据,则可以使用具有JSONP的库在域之间发送JSON数据。

例如,在 jQuery 中,您可以进行远程 JSON 调用:

jQuery.getJSON("http://www.someothersite.com/webservice?callback=?", function(result)
{
    doStuffWithResult(result);
});

由于调用是针对另一个域的,因此 jQuery 会自动使用一些技巧来进行跨域调用。 jQuery 将自动将 URL 中的 ? 替换为 Web 服务可用于格式化返回的 JSON 数据的回调函数名称。

如果您是控制 Web 服务的人,则可以通过获取名为"callback"的请求参数来处理 JSONP 请求,该参数将设置为您需要使用的回调函数名称。回调函数采用一个参数,即要发回的 JSON 数据。因此,如果回调参数设置为"jsonp2342342",则希望 Web 服务像这样响应:

jsonp2342342({key: value, key2: value});

如果您使用的 Web 服务已经支持 JSONP,则不必担心自己进行格式化。

可以编写一个简单的 .NET 页来检索远程页并将其显示在站点上:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
namespace Proxy
{
    public partial class _Proxy : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string proxyURL = string.Empty;
            try
            {
                proxyURL = HttpUtility.UrlDecode(Request.QueryString["u"].ToString());
            }
            catch { }
            if (proxyURL != string.Empty)
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(proxyURL);
                request.Method = "GET";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode.ToString().ToLower() == "ok")
                {
                    string contentType = response.ContentType;
                    Stream content = response.GetResponseStream();
                    StreamReader contentReader = new StreamReader(content);
                    Response.ContentType = contentType;
                    Response.Write(contentReader.ReadToEnd());
                }
            }
        }
    }
}

请参阅我关于它的帖子:http://www.johnchapman.name/aspnet-proxy-page-cross-domain-requests-from-ajax-and-javascript/

没有浏览器允许跨域脚本,尽管 w3c 在对 xmlHTTPRequest-object 的建议中为此留出了空间,但我们仍然需要等待一段时间才能看到它以安全的方式实现......

我将为寻求该问题的一般答案的人提供一个伪代码版本。

SomeAjaxAbstraction.Request('proxyScript', {
    parameters: {
        address: 'http://somewhere.com/someapi?some=query'
    }
});

然后在代理脚本中:

var address = GET['address'];
if(ValidUrl(address) && ConnectionAllowed(address)) {
    // Validating address and whitelisting services is an exercise to the reader
    var response = SomeHttpGetFunction(address);
    echo XssAndBadStuffFilter(response);
} else {
    // Handle errors
}