Table of Contents
在Web API中启用跨域访问
Home Web Front-end HTML Tutorial 跨域解决方案一:使用CORS实现跨域_html/css_WEB-ITnose

跨域解决方案一:使用CORS实现跨域_html/css_WEB-ITnose

Jun 24, 2016 am 11:20 AM

跨站HTTP请求(Cross-site HTTP request)是指发起请求的资源所在域不同于请求指向的资源所在域的HTTP请求。

比如说,我在Web网站A(www.a.com)中通过跨域解决方案一:使用CORS实现跨域_html/css_WEB-ITnose标签引入了B站的资源(www.b.com/images/1.jpg),那么A站会向B站发起一个跨站请求。

这种图片资源的跨站请求是被允许的,类似的跨站请求还有CSS文件,JavaScript文件等。

但是如果是在脚本中发起HTTP请求,出于安全考虑,会被浏览器限制。 比如,使用 XMLHttpRequest 对象发起 HTTP 请求就必须遵守  同源策略 。

所谓“同源策略”是指Web应用程序只能使用 XMLHttpRequest 对象向发起源所在域内发起HTTP请求,这个请求源和请求对象必须在一个域内。

举例来说,http://www.a.com,这个网址的协议是http,域名是www.a.com,端口默认是80。那么以下是它的同源情况:

  • http://www.a.com/index.html 同源
  • https://www.a.com/a.html 不同源(协议不同)
  • http://service.a.com/testService/test 不同源(域名不同)
  • http://www.b.com/index.html 不同源(域名不同)
  • http://www.a.com:8080/index.html 不同源(端口不同)

为了开发出更强大,更丰富的Web应用,跨域请求是很常见的,那么如何在不舍弃安全的情况下进行跨域请求呢?

W3C推荐了一种新的机制,即跨源资源共享( Cross-Origin Resource Sharing (CORS) )。

跨源资源共享(CORS)是通过客户端+服务端协作声明的方式来确保请求安全的。服务端会在HTTP请求头中增加一系列HTTP请求参数(例如Access-Control-Allow-Origin等),来限制哪些域的请求和哪些请求类型可以接受,而客户端在发起请求时必须声明自己的源(Orgin),否则服务器将不予处理,如果客户端不作声明,请求甚至会被浏览器直接拦截都到不了服务端。服务端收到HTTP请求后会进行域的比较,只有同域的请求才会处理。

一个使用CORS实现跨域请求的示例:

客户端:

function getHello() {            var xhr = new XMLHttpRequest();            xhr.open("post", "http://b.example.com/Test.ashx", true);            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");                // 声明请求源            xhr.setRequestHeader("Origin", "http://a.example.com");            xhr.onreadystatechange = function () {                if (xhr.readyState == 4 && xhr.status == 200) {                    var responseText = xhr.responseText;                    console.info(responseText);                }            }            xhr.send();        }
Copy after login

服务端:

public class Test : IHttpHandler    {        public void ProcessRequest(HttpContext context)        {            context.Response.ContentType = "text/plain";            // 声明接受所有域的请求            context.Response.AddHeader("Access-Control-Allow-Origin", "*");            context.Response.Write("Hello World");        }        public bool IsReusable        {            get            {                return false;            }        }    }
Copy after login

在Web API中启用跨域访问

CORS是服务端和客户端协作声明来确保请求安全的,因此,如果需要在Web API中启用CORS也需要进行相应配置。好在微软的ASP.NET团队提供了官方的支持跨域的解决方案,只需要在NuGet中添加即可。

然后在App_Start/WebApiConfig.cs进行如下配置即可实现跨域访问:

public static class WebApiConfig    {        public static void Register(HttpConfiguration config)        {            // Web API 配置和服务            // 将 Web API 配置为仅使用不记名令牌身份验证。            config.SuppressDefaultHostAuthentication();            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));            // Web API 路由            config.MapHttpAttributeRoutes();            config.Routes.MapHttpRoute(                name: "DefaultApi",                routeTemplate: "api/{controller}/{id}",                defaults: new { id = RouteParameter.Optional }            );            // 允许Web API跨域访问            EnableCrossSiteRequests(config);            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));        }        private static void EnableCrossSiteRequests(HttpConfiguration config) {            var cors = new EnableCorsAttribute(              origins: "*",              headers: "*",              methods: "*"              );            config.EnableCors(cors);        }    }
Copy after login

由于IE10以下浏览器不支持CORS,所以目前在国内CORS并不是主流的跨域解决方案,但是随着windows 10的发布,IE的逐渐衰落,可以预见,在不远的将来CORS将成为跨域的标准解决方案。

demo下载(bd36)

参考资料:

https://www.w3.org/TR/cors/

http://www.ruanyifeng.com/blog/2016/04/cors.html

https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is HTML easy to learn for beginners? Is HTML easy to learn for beginners? Apr 07, 2025 am 12:11 AM

HTML is suitable for beginners because it is simple and easy to learn and can quickly see results. 1) The learning curve of HTML is smooth and easy to get started. 2) Just master the basic tags to start creating web pages. 3) High flexibility and can be used in combination with CSS and JavaScript. 4) Rich learning resources and modern tools support the learning process.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

Gitee Pages static website deployment failed: How to troubleshoot and resolve single file 404 errors? Gitee Pages static website deployment failed: How to troubleshoot and resolve single file 404 errors? Apr 04, 2025 pm 11:54 PM

GiteePages static website deployment failed: 404 error troubleshooting and resolution when using Gitee...

What is an example of a starting tag in HTML? What is an example of a starting tag in HTML? Apr 06, 2025 am 12:04 AM

AnexampleofastartingtaginHTMLis,whichbeginsaparagraph.StartingtagsareessentialinHTMLastheyinitiateelements,definetheirtypes,andarecrucialforstructuringwebpagesandconstructingtheDOM.

How to use CSS3 and JavaScript to achieve the effect of scattering and enlarging the surrounding pictures after clicking? How to use CSS3 and JavaScript to achieve the effect of scattering and enlarging the surrounding pictures after clicking? Apr 05, 2025 am 06:15 AM

To achieve the effect of scattering and enlarging the surrounding images after clicking on the image, many web designs need to achieve an interactive effect: click on a certain image to make the surrounding...

HTML, CSS, and JavaScript: Essential Tools for Web Developers HTML, CSS, and JavaScript: Essential Tools for Web Developers Apr 09, 2025 am 12:12 AM

HTML, CSS and JavaScript are the three pillars of web development. 1. HTML defines the web page structure and uses tags such as, etc. 2. CSS controls the web page style, using selectors and attributes such as color, font-size, etc. 3. JavaScript realizes dynamic effects and interaction, through event monitoring and DOM operations.

How to implement adaptive layout of Y-axis position in web annotation? How to implement adaptive layout of Y-axis position in web annotation? Apr 04, 2025 pm 11:30 PM

The Y-axis position adaptive algorithm for web annotation function This article will explore how to implement annotation functions similar to Word documents, especially how to deal with the interval between annotations...

See all articles