我们知道通过在页面中使用JavaScript调用微软的XMLDOM/XMLHTTP组件,可以方便的在页面中各种远程的资源,如网页和XML数据。不过由于IE默认安全级别的限制,我们并不能通过XMLDOM/XMLHTTP访问不同域的数据源。也就是说,www.siteA.com不能访问www.siteB.com里的页面。我们可以通过一个简单的本地页面代理来帮我们实现这个功能。新的流程将是: siteA.com/local.aspx (JavaScript) -> siteA.com/agent.aspx?url=siteB.com/data.xml -> siteB.com/data.xml
代码很简单,支持POST方式,但是GET方式的时候,URL里的其他参数目前都没有处理。
代码很简单,支持POST方式,但是GET方式的时候,URL里的其他参数目前都没有处理。
<%@ Page Language="C#" ClassName="PageAgent" ValidateRequest="false" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Net" %>
<script type="text/C#" runat="server">
protected override void OnLoad(EventArgs e)
{
Response.Clear();
string url = Request.QueryString["url"];
if (null == url || url.Trim().Length == 0)
{
Response.End();
return;
}
try
{
WebRequest request = WebRequest.Create(url);
request.Method = Request.RequestType;
request.ContentType = Request.ContentType;
int reads = 0;
byte[] buffer = new byte[512];
if (Request.RequestType.Equals("POST", StringComparison.InvariantCultureIgnoreCase))
{
if (null != Request.Form) {
using (Stream s = request.GetRequestStream())
{
while ((reads = Request.InputStream.Read(buffer, 0, buffer.Length)) > 0)
{
s.Write(buffer, 0, reads);
}
s.Flush();
}
}
}
WebResponse response = request.GetResponse();
Response.ContentType = response.ContentType;
using (Stream s = response.GetResponseStream())
{
while ((reads = s.Read(buffer, 0, buffer.Length)) > 0)
{
Response.OutputStream.Write(buffer, 0, reads);
}
}
response.Close();
}
catch
{
}
Response.End();
}
</script>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Net" %>
<script type="text/C#" runat="server">
protected override void OnLoad(EventArgs e)
{
Response.Clear();
string url = Request.QueryString["url"];
if (null == url || url.Trim().Length == 0)
{
Response.End();
return;
}
try
{
WebRequest request = WebRequest.Create(url);
request.Method = Request.RequestType;
request.ContentType = Request.ContentType;
int reads = 0;
byte[] buffer = new byte[512];
if (Request.RequestType.Equals("POST", StringComparison.InvariantCultureIgnoreCase))
{
if (null != Request.Form) {
using (Stream s = request.GetRequestStream())
{
while ((reads = Request.InputStream.Read(buffer, 0, buffer.Length)) > 0)
{
s.Write(buffer, 0, reads);
}
s.Flush();
}
}
}
WebResponse response = request.GetResponse();
Response.ContentType = response.ContentType;
using (Stream s = response.GetResponseStream())
{
while ((reads = s.Read(buffer, 0, buffer.Length)) > 0)
{
Response.OutputStream.Write(buffer, 0, reads);
}
}
response.Close();
}
catch
{
}
Response.End();
}
</script>