ajax请求跨域设置代理_ASP.NET代理页面–用于来自AJAX和JavaScript的跨域请求

ajax请求跨域设置代理

One of the pain points with developing AJAX, JavaScript, JQuery, and other client-side behaviors is that JavaScript doesn’t allow for cross domain request for pulling content. For example, JavaScript code on

开发AJAX,JavaScript,JQuery和其他客户端行为的痛苦之一是JavaScript不允许跨域请求来提取内容。 例如,JavaScript代码

www.johnchapman.name could not pull content or data from www.johnchapman.name无法从 www.bing.com.  I have found this particularly painful when doing SharePoint development. www.bing.com提取内容或数据。 在进行SharePoint开发时,我发现这特别痛苦。

One way to overcome this issue is by using a server-side proxy on the site running the JavaScript code. There is already are well documented PHP solutions on the web, however I couldn’t find very many .NET-based solutions. This simple C# code takes the URL passed to it through the URL encoded query string, retrieves the content of the URL using an HttpWebRequest and outputs in the original form it as if it were content on the site.

解决此问题的一种方法是在运行JavaScript代码的站点上使用服务器端代理。 Web上已经有记录良好PHP解决方案,但是我找不到很多基于.NET的解决方案。 这个简单的C#代码采用通过URL编码的查询字符串传递给它的URL,使用HttpWebRequest检索URL的内容,并以原始形式输出,就好像它是网站上的内容一样。

The following code can be added to an ASP.NET application or to SharePoint.  For SharePoint, you can place the two files (Proxy.aspx and Proxy.aspx.cs) into the "_layouts" folder (c:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\LAYOUTS).

可以将以下代码添加到ASP.NET应用程序或SharePoint中。 对于SharePoint,您可以将两个文件(Proxy.aspx和Proxy.aspx.cs)放入“ _layouts”文件夹(c:\ Program Files \ Common Files \ Microsoft Shared \ Web服务器扩展\ 12 \ TEMPLATE \ LAY OUTS)。

Please Note: To keep this example simple and to the point it does not contain any error exception handling and such.  You can modify this code and add error handling as you see fit.  Also, allowing all websites to be proxied through your site could allow for malicious site content to appear as if they are coming from your site.  The Query String method below is not recommended for use on publicly accessible websites, instead use an ID in the Query String and lookup the actual URL from a database.  This will put you in complete control of the sites allowed to be proxied.

请注意:为了使本示例简单明了,该示例不包含任何错误异常处理等。 您可以根据需要修改此代码并添加错误处理。 同样,允许所有网站都通过您的网站进行代理可能会使恶意网站内容看起来像是来自您的网站。 不建议将以下查询字符串方法用于可公开访问的网站,而应在查询字符串中使用ID并从数据库中查找实际URL。 这将使您完全控制允许代理的站点。

 Complete Proxy.aspx.cs

完整的Proxy.aspx.cs

using System;
using System.Collections.Generic;
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.cs Breakdown

Proxy.aspx.cs细目分类

You will need to make sure at least the above listed "using" references have been added to the code-behind and that code is added to the Page_Load section of the code-behind.

您将需要确保至少上面列出的“使用”引用已添加到代码隐藏中,并且该代码已添加到代码隐藏的Page_Load部分中。

Since we are using a Query String to determine which page we are retrieving for the proxy in this example, we will need to get the value of the Query String and if no value is found, not to attempt to retrieve anything.  If you wanted to you could hard code a URL in the code if it was not going to be reused for any other pages.  Also, you could store the URL's in a database and use an ID in the Query String rather than putting the URL in the Query String.  It is important to remember that Query Strings only support certain characters.  If you have special characters it is important to URL Encode the Query String.  This site can be used to create URL Encoded strings for you:

由于在此示例中,由于我们使用查询字符串来确定要为代理检索的页面,因此我们将需要获取查询字符串的值,如果找不到值,则不要尝试检索任何内容。 如果您愿意,可以在代码中对URL进行硬编码,前提是该URL不会被其他页面重用。 另外,您可以将URL存储在数据库中,并在查询字符串中使用ID,而不是将URL放在查询字符串中。 请记住,查询字符串仅支持某些字符,这一点很重要。 如果您有特殊字符,则对URL编码查询字符串很重要。 该站点可用于为您创建URL编码的字符串:

http://www.albionresearch.com/misc/urlencode.php. http://www.albionresearch.com/misc/urlencode.php

If a value was found for the Query String in this example, we will create a new HttpWebRequest.  If you would like more information on the HttpWebRequest class, visit the following MSDN page:

如果在此示例中找到了查询字符串的值,我们将创建一个新的HttpWebRequest。 如果您想了解有关HttpWebRequest类的更多信息,请访问下面的MSDN页面:

http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx. http://msdn.microsoft.com/zh-CN/library/system.net.httpwebrequest.aspx

Using the request's GetResponse() method, we get a response (the remote page content).  However, we first need to make sure that we received a valid response ("ok").  We might not receive a valid response if we receive a 404 Not Found, 500 Internal Server Error, 401 Unauthorized or other normal HTTP error.

使用请求的GetResponse()方法,我们得到一个响应(远程页面内容)。 但是,我们首先需要确保我们收到了有效的回复(“确定”)。 如果我们收到404找不到,500内部服务器错误,401未经授权或其他正常的HTTP错误,则可能不会收到有效的响应。

If our response is OK, we use the Stream (data) of the response and output it to the page content.

如果响应正常,则使用响应的流(数据)并将其输出到页面内容。

Note: After the "if (response.StatusCode.ToString().ToLower() == "ok") { … }" snippet, you could add an else statement to output the StatusCode to an error log so that you can troubleshoot if necessary.  

注意:在“ if(response.StatusCode.ToStr ing()。ToLo wer()==“ ok”){…}“代码段,您可以添加else语句以将StatusCode输出到错误日志,以便在必要时进行故障排除。

This tutorial shows a simplified method for retrieving remote content and displaying it on your site so that AJAX, JQuery, JavaScript, etc can access to remote content.  When using this code, it is important to consider security concerns and error handling to ensure the best implementation of a proxy page.

本教程显示了一种简化的方法,用于检索远程内容并将其显示在您的站点上,以便AJAX,JQuery,JavaScript等可以访问远程内容。 使用此代码时,重要的是要考虑安全问题和错误处理,以确保最佳实现代理页面。

Proxy.aspx

Proxy.aspx

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

The Proxy.aspx page is simply blank except for the Page tag. When passing the URL to the query string, it is important that it is URL encoded. This helps to prevent query strings of the remote site URL from interfering with the Proxy page.

除了Page标记外,Proxy.aspx页只是空白。 将URL传递到查询字符串时,重要的是URL编码。 这有助于防止远程站点URL的查询字符串干扰“代理”页面。

Example Usage

用法示例

http://www.yourdotnetapplication.com/proxy.aspx?u=http%3a%2f%2fwww.google.com
http://www.yoursharepointsite.com/_layouts/proxy.aspx?u=http%3a%2f%2fwww.google.com

The original article as well as source code can be found at:

原始文章以及源代码可以在以下位置找到:

http://www.johnchapman.name/aspnet-proxy-page-cross-domain-requests-from-ajax-and-javascript/ http://www.johnchapman.name/aspnet-proxy-page-cross-domain-requests-from-ajax-and-javascript/

翻译自: https://www.experts-exchange.com/articles/3612/ASP-NET-Proxy-Page-Used-for-Cross-Domain-Requests-from-AJAX-and-JavaScript.html

ajax请求跨域设置代理

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值