ASP.NET写的AJAX跨域代理(收藏)

来源:互联网 发布:部落冲突 知乎 编辑:程序博客网 时间:2024/05/01 16:11

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

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

view plaincopy to clipboardprint?
  1. using System;   
  2.   
  3. using System.Data;   
  4.   
  5. using System.Text;   
  6.   
  7. using System.IO;   
  8.   
  9. using System.Configuration;   
  10.   
  11. using System.Web;   
  12.   
  13. using System.Web.Security;   
  14.   
  15. using System.Web.UI;   
  16.   
  17. using System.Net;   
  18.   
  19.   
  20.   
  21. public partial class Proxy : System.Web.UI.Page   
  22.   
  23. {   
  24.   
  25.     protected void Page_Load(object sender, EventArgs e)   
  26.   
  27.     {   
  28.   
  29.         string url = Request["URL"].ToString();   
  30.   
  31.         string clientversion = Request["ClientVersion"].ToString();   
  32.   
  33.         string customservice = string.Empty;   
  34.   
  35.         string URL = string.Empty;   
  36.   
  37.         if (Request["CustomService"] != null)//注意不能要form的参数   
  38.   
  39.         {   
  40.   
  41.             customservice = Request["CustomService"].ToString();   
  42.   
  43.             URL = url + "&CustomService=" + customservice+ "&ClientVersion=" + clientversion ;   
  44.   
  45.         }   
  46.   
  47.         else  
  48.   
  49.         {   
  50.   
  51.             URL = url + "&ClientVersion=" + clientversion;   
  52.   
  53.         }   
  54.   
  55.         string arcxml = Request["ArcXML"].ToString();   
  56.   
  57.         byte[] postBytes = Encoding.UTF8.GetBytes(arcxml);   
  58.   
  59.   
  60.   
  61.         string result = string.Empty;   
  62.   
  63.         HttpWebRequest HttpWReq =(HttpWebRequest)WebRequest.Create(URL);   
  64.   
  65.         HttpWReq.Method = "Post";   
  66.   
  67.         HttpWReq.ContentType = "application/x-www-form-urlencoded";   
  68.   
  69.         HttpWReq.ContentLength = postBytes.Length;   
  70.   
  71.         using (Stream reqStream = HttpWReq.GetRequestStream())   
  72.   
  73.         {   
  74.   
  75.             reqStream.Write(postBytes, 0, postBytes.Length);   
  76.   
  77.         }   
  78.   
  79.   
  80.   
  81.         HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();   
  82.   
  83.         StreamReader reader = new StreamReader(HttpWResp.GetResponseStream(), Encoding.UTF8);   
  84.   
  85.         result = reader.ReadToEnd();   
  86.   
  87.         //HttpWResp.Close();   
  88.   
  89.   
  90.   
  91.         Response.Write(result);   
  92.   
  93.         Response.End();   
  94.   
  95.     }   
  96.   
  97. }