对于想了解Ajax跨域设置Access-Control-Allow-Origin的读者,本文将是一篇不可错过的文章,我们将详细介绍ajax跨域设置请求头,并且为您提供关于(服务端处理)ajax设置Ac
对于想了解Ajax跨域设置Access-Control-Allow-Origin的读者,本文将是一篇不可错过的文章,我们将详细介绍ajax跨域设置请求头,并且为您提供关于(服务端处理)ajax 设置Access-Control-Allow-Origin实现跨域访问、.Net 通过设置Access-Control-Allow-Origin来实现跨域访问、Access-Control-Allow-Origin 与 Ajax 跨域、Access-Control-Allow-Origin与Ajax跨域的有价值信息。
本文目录一览:- Ajax跨域设置Access-Control-Allow-Origin(ajax跨域设置请求头)
- (服务端处理)ajax 设置Access-Control-Allow-Origin实现跨域访问
- .Net 通过设置Access-Control-Allow-Origin来实现跨域访问
- Access-Control-Allow-Origin 与 Ajax 跨域
- Access-Control-Allow-Origin与Ajax跨域
Ajax跨域设置Access-Control-Allow-Origin(ajax跨域设置请求头)
传统的跨域请求没有好的解决方案,无非就是jsonp和iframe,随着跨域请求的应用越来越多,W3C提供了跨域请求的标准方案(Cross-Origin Resource Sharing)。IE8、Firefox3.5 及其以后的版本、chrome浏览器、Safari 4 等已经实现了 Cross-Origin Resource Sharing 规范,实现了跨域请求。
在服务器响应客户端的时候,带上Access-Control-Allow-Origin头信息。
Ajax跨域问题:
解决方法:
response.setHeader("Access-Control-Allow-Origin","*");
注意: 如果设置 Access-Control-Allow-Origin:*,则允许所有域名的脚本访问该资源; Access-Control-Allow-Origin:http://www.ql1d.com,允许特定的域名访问。
(服务端处理)ajax 设置Access-Control-Allow-Origin实现跨域访问
原文:http://www.jb51.cc/article/p-harvrahb-bkb.html
ajax跨域访问是一个老问题了,解决方法很多,比较常用的是JSONP方法,JSONP方法是一种非官方方法,而且这种方法只支持GET方式,不如POST方式安全。
即使使用jquery的jsonp方法,type设为POST,也会自动变为GET。
官方问题说明:
“script”: Evaluates the response as JavaScript and returns it as plain text. disables caching by appending a query string parameter,“_=[TIMESTAMP]“,to the URL unless the cache option is set to true.Note: This will turn POSTs into GETs for remote-domain requests.
如果跨域使用POST方式,可以使用创建一个隐藏的iframe来实现,与ajax上传图片原理一样,但这样会比较麻烦。
因此,通过设置Access-Control-Allow-Origin来实现跨域访问比较简单。
例如:客户端的域名是www.client.com,而请求的域名是www.server.com
如果直接使用ajax访问,会有以下错误
XMLHttpRequest cannot load http://www.server.com/server.PHP. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://www.client.com' is therefore not allowed access.
在被请求的Response header中加入
- //指定允许其他域名访问
- header('Access-Control-Allow-Origin:*');
- //响应类型
- header('Access-Control-Allow-Methods:POST');
- //响应头设置
- header('Access-Control-Allow-Headers:x-requested-with,content-type');
就可以实现ajax POST跨域访问了。
代码如下:
client.html路径:http://www.client.com/client.html
.Net 通过设置Access-Control-Allow-Origin来实现跨域访问
[toc]
# 前言
.Net 通过设置Access-Control-Allow-Origin来实现跨域访问,具体哪里可以设置Access-Control-Allow-Origin呢?
- web.config中可以设置;
- 在IIS服务器站点的功能视图中设置HTTP响应标头;
- 通过nginx代理服务器进行设置;
- 在每个api接口上添加响应头;
- 写一个拦截器,应用到所有控制器上,在拦截器里控制来访域名,动态设置Access-Control-Allow-Origin的值;
本文主要详细说下第四种和第五种方式,第五种方式也是对第四种方式的一种封装;
# 为每个API接口单独添加响应头
1、针对 ASP.NET MVC 项目的Controllers
public class Default1Controller : Controller
{
public ActionResult Test()
{
ControllerContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
/*
--Your code
*/
return Json("hello");
}
}
2、针对 ASP.NET Web API项目的Controllers
public class TestController : ApiController
{
public HttpResponseMessage Get(int id)
{
var response = Request.CreateResponse(HttpStatusCode.OK, new {Name="lily",age=10});
response.Headers.Add("Access-Control-Allow-Origin", "*");
//response.Headers.Add("X-Pagination", "TestHeader");
//response.Headers.Add("Access-Control-Expose-Headers", "X-Pagination");
return response;
}
}
3、针对ASP.NET Web Forms项目中的处理程序
public class TestHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.AddHeader("Access-Control-Allow-Origin", "http://example.com");
context.Response.AddHeader("Access-Control-Allow-Headers", "*");
context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
context.Response.AddHeader("Access-Control-Allow-Credentials", "true");
//context.Response.AddHeader("TestHeaderToExpose", "test");
//context.Response.AddHeader("Access-Control-Expose-Headers", "TestHeaderToExpose");
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
}
public bool IsReusable
{
get
{
return false;
}
}
}
# 封装一个拦截器,便于应用到控制器及接口上
1、针对 ASP.NET MVC 项目的Controllers
创建一个attribute:
using System.Web.Mvc;
namespace AllowCross.App_Code
{
public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
//actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
//actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Headers", "*");
//actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
//context.Response.AddHeader("TestHeader", "test");
//actionExecutedContext.Response.Headers.Add("Access-Control-Expose-Headers", "TestHeader");
base.OnActionExecuting(filterContext);
}
}
}
将该attribute添加到action上:
using AllowCross.App_Code;
namespace AllowCross.Controllers
{
public class Default1Controller : Controller
{
[AllowCrossSiteJson]
public ActionResult Test()
{
return Json("hello");
}
}
}
2、针对 ASP.NET Web API项目
创建一个attribute:
using System.Web.Http.Filters;
namespace WepApiTest.App_Code
{
public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext.Response != null)
{
actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
//actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
//actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Headers", "*");
//actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
//context.Response.AddHeader("TestHeader", "test");
//actionExecutedContext.Response.Headers.Add("Access-Control-Expose-Headers", "TestHeader");
}
base.OnActionExecuted(actionExecutedContext);
}
}
}
将该attribute添加到acion上:
using WepApiTest.App_Code;
namespace WepApiTest.Controllers
{
public class DefaultController : ApiController
{
[AllowCrossSiteJson]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
}
也可以将该attribute添加到整个controller上:
using WepApiTest.App_Code;
namespace WepApiTest.Controllers
{
[AllowCrossSiteJson]
public class DefaultController : ApiController
{
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
}
3、针对 ASP.NET Web API 2 还可以使用库:Microsoft.AspNet.WebApi.Cors
3.1 使用nuget安装Microsoft.AspNet.WebApi.Cors
使用命令:
Install-Package Microsoft.AspNet.WebApi.Cors
使用管理器:
3.2 打开App_Start/WebApiConfig.cs文件,在WebApiConfig.Register方法中配置WebApi.Cors
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//配置WebApi.Cors
config.EnableCors();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
3.3 在Controller上添加[EnableCors]属性
using System.Web.Http;
using System.Web.Http.Cors;
namespace WepApiTest.Controllers
{
[EnableCors(origins: "http://WepApiTest.com", headers: "*", methods: "*")]
public class TestController : ApiController
{
// GET: api/Test
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
}
3.3 在Controller中的action上添加[EnableCors]属性
using System.Web.Http;
using System.Web.Http.Cors;
namespace WepApiTest.Controllers
{
public class TestController : ApiController
{
// GET: api/Test
[EnableCors(origins: "http://WepApiTest.com", headers: "*", methods: "*")]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
}
3.4 如果想应用到所有的api controller上,在WebApiConfig.Register方法中进行如下配置
using System.Web.Http;
using System.Web.Http.Cors;
namespace WebApplication2
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//配置WebApi.Cors
var cors = new EnableCorsAttribute("www.example.com", "*", "*");
config.EnableCors(cors);
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
3.5 设置origins、HTTP methods、request headers示例
// Allow CORS for all origins. (Caution!)
[EnableCors(origins: "*", headers: "*", methods: "*")]
[EnableCors(origins: "http://www.justsoso.com,http://www.example.com",
headers: "*", methods: "*")]
[EnableCors(origins: "http://www.example.com", headers: "*", methods: "get,post")]
[EnableCors(origins: "http://example.com",
headers: "accept,content-type,origin,x-my-header", methods: "*")]
3.6 Pass credentials in cross-origin requests
Credentials require special handling in a CORS request. By default, the browser does not send any credentials with a cross-origin request. Credentials include cookies as well as HTTP authentication schemes. To send credentials with a cross-origin request, the client must set XMLHttpRequest.withCredentials to true.
Using XMLHttpRequest directly:
var xhr = new XMLHttpRequest();
xhr.open(''get'', ''http://www.example.com/api/test'');
xhr.withCredentials = true;
In jQuery:
$.ajax({
type: ''get'',
url: ''http://www.example.com/api/test'',
xhrFields: {
withCredentials: true
}
In addition, the server must allow the credentials. To allow cross-origin credentials in Web API, set the SupportsCredentials property to true on the [EnableCors] attribute:
[EnableCors(origins: "http://myclient.azurewebsites.net", headers: "*",
methods: "*", SupportsCredentials = true)]
If this property is true, the HTTP response will include an Access-Control-Allow-Credentials header. This header tells the browser that the server allows credentials for a cross-origin request.
If the browser sends credentials, but the response does not include a valid Access-Control-Allow-Credentials header, the browser will not expose the response to the application, and the AJAX request fails.
Be careful about setting SupportsCredentials to true, because it means a website at another domain can send a logged-in user''s credentials to your Web API on the user''s behalf, without the user being aware. The CORS spec also states that ==setting origins to "*" is invalid if SupportsCredentials is true==.
3.7 浏览器支持情况
库Web API CORS是服务端的处理方法,还必须要求客户端支持CORS,支持情况请查看该地址: https://caniuse.com/#feat=cors
# 低版本IE实现跨域
参考:Cross-Domain AJAX for IE8 and IE9
# 参考
Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method Microsoft.AspNet.WebApi.Cors 跨域资源共享 CORS 详解
——————————————————————————————————————————————
原文出处:https://www.cnblogs.com/willingtolove/p/11175599.html
Access-Control-Allow-Origin 与 Ajax 跨域
问题
在某域名下使用 Ajax 向另一个域名下的页面请求数据,会遇到跨域问题。另一个域名必须在 response 中添加 Access-Control-Allow-Origin
的 header,才能让前者成功拿到数据。
这句话对吗?如果对,那么流程是什么样的?
跨域
怎样才能算跨域?协议,域名,端口都必须相同,才算在同一个域。
参考:
- Are different ports on the same server considered cross-domain? (Ajax-wise)
- 同事李栋的博客:跨源资源共享
当跨域访问时,浏览器会发请求吗
这是真正困扰我们的问题,因为我们不清楚浏览器会怎么做。它会不会检查到你要请求的地址不是同一个域的,直接就禁止了呢?
我在 jsbin 上 做了一个试验 ,使用 Chrome 打开。当点击 “Run with Js” 时,控制台上会打出:
XMLHttpRequest cannot load http://google.com/. No ''Access-Control-Allow-Origin'' header is present on the requested resource. Origin ''http://run.jsbin.io'' is therefore not allowed access.
但开发者工具的”Network” 栏并没有任何记录。它到底发请求了没?
我又使用 python -m SimpleHTTPServer
在本地创建了一个小服务器,然后把地址改成它,结果发现在 python 这边的确打印出请求来了,可见浏览器的确发出了请求。
Access-Control-Allow-Origin
现在该 Access-Control-Allow-Origin
出场了。只有当目标页面的 response 中,包含了 Access-Control-Allow-Origin
这个 header,并且它的值里有我们自己的域名时,浏览器才允许我们拿到它页面的数据进行下一步处理。如:
Access-Control-Allow-Origin: http://run.jsbin.io
如果它的值设为 *
,则表示谁都可以用:
Access-Control-Allow-Origin: *
没错,在产品环境中,没人会用 *
你可以阅读下面这篇文章了解更多,并可找到其中的”Run Sample” 链接,实际体验一下:
http://www.html5rocks.com/en/tutorials/cors/
public HttpResponseMessage Get(string fatherId)
{
string str = JsonConvert.SerializeObject(GetAleCategorysByFid(fatherId), Formatting.Indented);
HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
result.Headers.Add("Access-Control-Allow-Origin", "*");
return result;
}
Access-Control-Allow-Origin与Ajax跨域
问题
在某域名下使用Ajax向另一个域名下的页面请求数据,会遇到跨域问题。另一个域名必须在response中添加 Access-Control-Allow-Origin
的header,才能让前者成功拿到数据。
这句话对吗?如果对,那么流程是什么样的?
跨域
怎样才能算跨域?协议,域名,端口都必须相同,才算在同一个域。
参考:
- Are different ports on the same server considered cross-domain? (Ajax-wise)
- 同事李栋的博客:跨源资源共享
当跨域访问时,浏览器会发请求吗
这是真正困扰我们的问题,因为我们不清楚浏览器会怎么做。它会不会检查到你要请求的地址不是同一个域的,直接就禁止了呢?
我在jsbin上 做了一个试验 ,使用Chrome打开。当点击“Run with Js”时,控制台上会打出:
XMLHttpRequest cannot load http://google.com/. No ''Access-Control-Allow-Origin'' header is present on the requested resource. Origin ''http://run.jsbin.io'' is therefore not allowed access.
但开发者工具的”Network”栏并没有任何记录。它到底发请求了没?
我又使用 python -m SimpleHTTPServer
在本地创建了一个小服务器,然后把地址改成它,结果发现在python这边的确打印出请求来了,可见浏览器的确发出了请求。
Access-Control-Allow-Origin
现在该 Access-Control-Allow-Origin
出场了。只有当目标页面的response中,包含了 Access-Control-Allow-Origin
这个header,并且它的值里有我们自己的域名时,浏览器才允许我们拿到它页面的数据进行下一步处理。如:
Access-Control-Allow-Origin: http://run.jsbin.io
如果它的值设为 *
,则表示谁都可以用:
Access-Control-Allow-Origin: *
没错,在产品环境中,没人会用 *
你可以阅读下面这篇文章了解更多,并可找到其中的”Run Sample”链接,实际体验一下:
http://www.html5rocks.com/en/tutorials/cors/
public HttpResponseMessage Get(string fatherId)
{
string str = JsonConvert.SerializeObject(GetAleCategorysByFid(fatherId), Formatting.Indented);
HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
result.Headers.Add("Access-Control-Allow-Origin", "*");
return result;
}
我们今天的关于Ajax跨域设置Access-Control-Allow-Origin和ajax跨域设置请求头的分享就到这里,谢谢您的阅读,如果想了解更多关于(服务端处理)ajax 设置Access-Control-Allow-Origin实现跨域访问、.Net 通过设置Access-Control-Allow-Origin来实现跨域访问、Access-Control-Allow-Origin 与 Ajax 跨域、Access-Control-Allow-Origin与Ajax跨域的相关信息,可以在本站进行搜索。
本文标签: