最近做东西遇到了ajax跨域(cross domain)访问的问题,最后采用了Application Proxies 方式解决,即在本域内放置一个代理文件(视本域支持的开发语言选定asp、asp.net或是其他),此代理文件将url参数(QueryString)发送到目标域对应页面获取html代码,然后输出。ajax直接访问这个代理文件以达到跨域的目的。
基于asp.net的跨域访问代理文件c#代码如下:
另外还有基于asp和php的实现,不再列出,感兴趣的可以下载包含这三个文件的压缩包:
https://files.cnblogs.com/cncxz/ajaxProxy.rar
基于asp.net的跨域访问代理文件c#代码如下:
<%@ Page Language="C#" AutoEventWireup="true" ResponseEncoding="utf-8" %>
<%@ Import Namespace=System.Net %>
<%@ Import Namespace=System.IO %>
<script runat="server">
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
string sourceUrl = "http://devspy.net";
this.Page.Response.Write(TransferHtmlPage(string.Concat(sourceUrl, "?", this.Page.Request.QueryString)));
}
public string TransferHtmlPage(string url)
{
string result = string.Empty;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
result = reader.ReadToEnd();
}
catch(Exception ex)
{
return string.Format(@"<p style='color:red;text-align:center;'>服务器获取文件内容出错:{0}</p>", ex.Message);
}
if (!CheckVersionWaterMark(result))
return @"<p style='color:red;text-align:center;'>版本水印失效,请联系相关技术人员。</p>";
return result;
}
public bool CheckVersionWaterMark(string inputString)
{
return true;//不验证水印了
//string pattern = "WaterMark";
//return Regex.IsMatch(inputString, pattern, RegexOptions.IgnoreCase);
}
</script>
<%@ Import Namespace=System.Net %>
<%@ Import Namespace=System.IO %>
<script runat="server">
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
string sourceUrl = "http://devspy.net";
this.Page.Response.Write(TransferHtmlPage(string.Concat(sourceUrl, "?", this.Page.Request.QueryString)));
}
public string TransferHtmlPage(string url)
{
string result = string.Empty;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
result = reader.ReadToEnd();
}
catch(Exception ex)
{
return string.Format(@"<p style='color:red;text-align:center;'>服务器获取文件内容出错:{0}</p>", ex.Message);
}
if (!CheckVersionWaterMark(result))
return @"<p style='color:red;text-align:center;'>版本水印失效,请联系相关技术人员。</p>";
return result;
}
public bool CheckVersionWaterMark(string inputString)
{
return true;//不验证水印了
//string pattern = "WaterMark";
//return Regex.IsMatch(inputString, pattern, RegexOptions.IgnoreCase);
}
</script>
另外还有基于asp和php的实现,不再列出,感兴趣的可以下载包含这三个文件的压缩包:
https://files.cnblogs.com/cncxz/ajaxProxy.rar