ASP.NET写的AJAX跨域代理

我用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();

    }

}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值