ASP.NET写的AJAX跨域代理

Posted by 蒋波涛 13 June,2008 Views (1)Comment

我用AJAX写了个ArcIMS的WebGIS,在做测试的时候链接的是网络上别的城市的数据,当然,不可避免就出现了跨域问题咯。AJAX跨域的本质是JS的问题,JS写的程序只允许访问本域内的数据,而跨域则受到限制,在IE中会弹出一个警告,在FF中直接就被终止了,所以我的这个WebGIS在解决跨域之前无法在FF中使用(如果数据在本域还是可以的)。

 好了,跨域解决的方法很简单,即在本域中新建一个不使用XHR对象发送请求并接收响应的程序即可,因此,asp、aspnet、jsp或servlet都能够担当此重任。下面是我写的一个aspnet代理:using System;
using System.Data;
using System.Text;
using System.IO;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Net;

public partial class Proxy : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string url = Request["URL"].ToString();
        string clientversion = Request["ClientVersion"].ToString();
        string customservice = string.Empty;
        string URL = string.Empty;
        if (Request["CustomService"] != null)//注意不能要form的参数
        {
            customservice = Request["CustomService"].ToString();
            URL = url + "&CustomService=" + customservice+ "&ClientVersion=" + clientversion ;
        }
        else
        {
            URL = url + "&ClientVersion=" + clientversion;
        }
        string arcxml = Request["ArcXML"].ToString();
        byte[] postBytes = Encoding.UTF8.GetBytes(arcxml);

        string result = string.Empty;
        HttpWebRequest HttpWReq =(HttpWebRequest)WebRequest.Create(URL);
        HttpWReq.Method = "Post";
        HttpWReq.ContentType = "application/x-www-form-urlencoded";
        HttpWReq.ContentLength = postBytes.Length;
        using (Stream reqStream = HttpWReq.GetRequestStream())
        {
            reqStream.Write(postBytes, 0, postBytes.Length);
        }

        HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
        StreamReader reader = new StreamReader(HttpWResp.GetResponseStream(), Encoding.UTF8);
        result = reader.ReadToEnd();
        //HttpWResp.Close();

        Response.Write(result);
        Response.End();
    }
}

 

Related Items

Categories : Ajax Tags : AJAX  ArcIMS  
Comments
2008-6-19 11:28:15

我猜测.NET LINK就是这样写的Haha

Posted by 蒋波涛 Gravatar Icon

Leave a comment

Or, take a look at Archives and Categories

目录

存档