65.9K
CodeProject 正在变化。 阅读更多。
Home

ASP.NET 代理页面 – 用于从 AJAX 和 JavaScript 发出的跨域请求

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0投票)

2013 年 10 月 11 日

CPOL

2分钟阅读

viewsIcon

95827

开发 AJAX、JavaScript、JQuery 和其他客户端行为的痛点之一是 JavaScript 不允许跨域

开发 AJAX、JavaScript、JQuery 和其他客户端行为的痛点之一是 JavaScript 不允许跨域请求来获取内容。例如,www.johnchapman.name 上的 JavaScript 代码无法从 www.bing.com 获取内容或数据。

解决此问题的一种方法是在运行 JavaScript 代码的站点上使用服务器端代理。Web 上已经有充分的 PHP 解决方案,但是,我没有找到很多基于 .NET 的解决方案。这段简单的 C# 代码通过 URL 编码的查询字符串传递给它的 URL,检索 URL 的内容,并将其输出,就好像它是站点上的内容一样。

Proxy.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;

namespace Proxy
{
    public partial class _Proxy : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string proxyURL = string.Empty;
            try
            {
                proxyURL = HttpUtility.UrlDecode(Request.QueryString["u"].ToString());
            }
            catch { }

            if (proxyURL != string.Empty)
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(proxyURL);
                request.Method = "GET";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                if (response.StatusCode.ToString().ToLower() == "ok")
                {
                    string contentType = response.ContentType;
                    Stream content = response.GetResponseStream();
                    StreamReader contentReader = new StreamReader(content);
                    Response.ContentType = contentType;
                    Response.Write(contentReader.ReadToEnd());
                }
            }
        }
    }
}

Proxy.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Proxy.aspx.cs" Inherits="Proxy._Proxy" % >

Proxy.aspx 页面除了 Page 标签外,只是空白。当将 URL 传递给查询字符串时,对它进行 URL 编码很重要。这有助于防止远程站点 URL 的查询字符串干扰 Proxy 页面。

 

示例用法

yoursite.com/proxy.aspx?u=http%3a%2f%2fwww.google.com

 

最初发布于:http://www.johnchapman.name/aspnet-proxy-page-cross-domain-requests-from-ajax-and-javascript/

 

将所有代码行添加到 try catch 中,因为错误可能发生在任何代码行中

    protected void getWebRequest()
    {

        try
        {

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.msn.com");
            request.Method = "GET";
            request.Proxy = null;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string contentType = response.ContentType;
            Stream content = response.GetResponseStream();
            StreamReader contentReader = new StreamReader(content);
            Response.ContentType = contentType;
            Response.Write(contentReader.ReadToEnd());

        }
        catch (Exception ee)
        {

            Response.Write(ee.Message.ToString());
        }
    }

 

© . All rights reserved.