Read Catalogue
- First, the Origin of cross-domain problems
- Two, cross-domain problem solving principle
- Three, cross-domain Problem resolution details
- 1. Scene description
- 2. Scene test
- Iv. Summary
Body
The last chapter summarizes the use of the Webapi Interface test tool, which is followed by another common problem with Webapi: cross-domain issues. This article mainly from the perspective of the instance to share the following cors to solve the cross-domain problem some details.
First, the Origin of cross-domain problems
Same-origin policy: For security reasons, the browser restricts cross-site requests originating in the script, and the browser requires JavaScript or cookies to only access content under the same domain.
It is for this reason that calls between our different projects are blocked by the browser. For example, our most common scenario: WEBAPI as a data service layer, it is a separate project, our MVC project as the Web display layer, this time in our MVC need to call Webapi inside the interface to take the data presented on the page. Since our Webapi and MVC are two different projects, there is a cross-domain problem that is mentioned above when we are running them.
Back to top second, cross-domain problem solving principle
Cors Full name Cross-origin Resource sharing, Chinese name cross-domain resource sharing. It solves the cross-domain problem by adding a corresponding identity to the HTTP request message and the response message to tell the browser which domain name it can access. For example, by adding this access-control-allow-origin:http://localhost:8081 to the response message, we support all requests in the http://localhost:8081 to access the system resources. Other more applications we do not list, you can go online to find.
Back to top three, cross-domain Problem resolution details
Here I'll combine a simple example to illustrate how to use cors to solve WEBAPI cross-domain issues.
Back to top 1, description of the scene
We created two new projects, one WEBAPI project (webapicors), and one MVC project (in Web). The WEBAPI project is responsible for providing interface services, and the MVC Project is responsible for page rendering. As follows:
Theweb and webapicors port numbers are "27239" and "27221", respectively. Web projects need to take data from the WEBAPICORSS project, it is clear that two project ports are different, so there is no homologous, if using the regular method of invocation there must be a cross-domain problem.
A simple introduction to the test code, the web has a HomeController
Class Homecontroller:controller { // get:home public return View ();}}
The corresponding index.cshtml
<Html><Head><MetaName= "Viewport"Content= "Width=device-width"/><Title>index</Title><ScriptSrc= "~/content/jquery-1.9.1.js"></Script><LinkHref= "~/content/bootstrap/css/bootstrap.css"Rel= "stylesheet"/><ScriptSrc= "~/content/bootstrap/js/bootstrap.js"></Script><ScriptSrc= "~/scripts/home/index.js"></script>< Span style= "COLOR: #0000ff" ></head><body> test result: <div id= "div_test" > </div> </body></html>
Index.js file
var apiurl = "http://localhost:27221/"; $ (function () { $.ajax ({ type: "Get", Url:apiurl + "Api/charging/getallchargingdata"functionif (status = = "Success") {$ ("#div_test"function (E {$ ("#div_test"). HTML ("Error"function () {}});});
The Webapicors project has a test WEBAPI service Chargingcontroller
PublicClass Chargingcontroller:apicontroller {///<summary> /// Get all data ///</summary> ///<returns> return data </returns>< Span style= "COLOR: #000000" > [HttpGet] public string Getallchargingdata () {return success "} /span>
The routing rules for configuring WEBAPI are called through action. WebApiConfig.cs file
PublicStaticclass Webapiconfig {publ IC static void Register ( Httpconfiguration config) {// Web API routing CONFIG. Maphttpattributeroutes (); Config. Routes.maphttproute (name: "defaultapi" "api/{controller}/{action}/{id}" new {ID = routeparameter.optional}); } }
Back to top 2, scene test 1) We do not do any processing, directly to the two projects to run up. See how it works.
IE Browser:
Google Chrome:
The results of another blogger is also very surprised, do not do any cross-domain processing, IE10, IE11 unexpectedly can directly request data success, and the same code IE8, IE9, Google Browser can not cross-domain access. The reason for this is to be found, it should be Microsoft moved something.
2) using cors across domains
First describe how cors is used, use NuGet to search for "microsoft.aspnet.webapi.cors" on the Webapicors project, install the first
Then configure the cross-domain in the WebApiConfig.cs folder under the App_start folder
PublicStaticClassWebapiconfig {PublicStaticvoidRegister (httpconfiguration config) {//Configure config across domains. Enablecors (New Enablecorsattribute ("* ", " * ", " * "// Web API route CONFIG. Maphttpattributeroutes (); Config. Routes.maphttproute (name: "defaultapi" "api/{controller}/{action}/{id}" new {ID = routeparameter.optional}); } }
We tentatively three "*", of course, when used in the project, it is generally necessary to specify which domain name can cross-domain, cross-domain operations and so on. This is described below.
IE10, IE11
Google Chrome
IE8, IE9
There's a new problem at this time, what's going on? I have set the cross-domain, how IE8, 9 or not? This time it is necessary to talk about Cors browser support issues. This map can be found all over the Web:
Describes the browser support for Cors, and you can see that IE8, 9 is partially supported. Online solutions are all Internet Explorer 8, 9 using Xdomainrequest objects to implement Cors. Is it so complicated? So Bo master all kinds of Baidu to find a solution. The last discovery is to specify JQuery.support.cors = True at the call , which solves the problem of IE8, 9. Specifically, in the Index.js .
JQuery.support.cors =true; var apiurl = "http://localhost:27221/" ;$ (function () {$.ajax ({type: "Get" functionif (Status = = "Success" " {$ ("#div_test" function (E) {$ ("#div_test"). HTML ("Error" function () {}});
The meaning of this sentence is to specify that the browser supports cross-domain. Originally IE9 above version of the browser, Google, Firefox and so on are supported by default cross-domain, and IE8, 9 but the default does not support cross-domain, we need to specify a bit. You can print jQuery.support.cors in your browser and see. Will this fix the problem after setting it up? Let's look at the effect:
Problem solved perfectly. As for the online cors on IE8, 9 solution xdomainrequest is going to be verified by the case.
3) Cors's specific parameter settings.
Above we use
Config. Enablecors (new Enablecorsattribute ("*" * "*"));
This sentence solves the cross-domain problem, which says that the * number is unsafe. Because it means that whenever someone knows your request URL, any request can access your resource. This is quite dangerous. So we need to do some configuration to restrict access. For example, our more common practice is as follows:
Configuration method One, in the Web. config (PS: These two images originate from: http://www.cnblogs.com/moretry/p/4154479.html)
Then in the Register method of the WebApiConfig.cs file
Configuration method Two, if you only want to do some API cross-domain, you can directly on the API class using the attribute annotation.
[Enablecors (Origins:"Http://localhost:8081/", Headers:"*", Methods:"Get,post,put,delete")]Publicclass Chargingcontroller:apicontroller {///<summary> /// Get all data ///</summary> ///<returns> return data </returns> [HttpGet] public string Getallchargingdata () { return "success" ; } }
Back to top four, summary
The above is a simple cors solution Webapi cross-domain problems, because bloggers use WEBAPI time is not long, so many theoretical points may not be mature, if there is said wrong, welcome to point out. Thank you, Bo Lord.
C # Advanced Series--webapi cross-domain problem solution: CORS