Note : This article is a personal study excerpt, the original address: http://www.cnblogs.com/landeanfen/p/5177176.html
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.
Two, 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.
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.
1. Scene description
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
Public class Homecontroller:controller { // get:home Public actionresult Index () { 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></Head><Body>Test Results:<DivID= "Div_test"> </Div></Body></HTML>
Index.js file
varApiurl = "http://localhost:27221/";$(function() {$.ajax ({type:"Get", Url:apiurl+ "Api/charging/getallchargingdata", data: {}, Success:function(data, status) {if(Status = = "Success") { $("#div_test"). HTML (data); }}, Error:function(e) {$ ("#div_test"). HTML ("Error")); }, Complete:function () { } });});
The Webapicors project has a test WEBAPI service Chargingcontroller
Public classChargingcontroller:apicontroller {/// <summary> ///get all the data/// </summary> /// <returns>Return Data</returns>[HttpGet] Public stringGetallchargingdata () {return "Success"; } }
The routing rules for configuring WEBAPI are called through action. WebApiConfig.cs file
Public Static classWebapiconfig { Public Static voidRegister (httpconfiguration config) {//Web API RoutingCONFIG. Maphttpattributeroutes (); Config. Routes.maphttproute (Name:"Defaultapi", Routetemplate:"Api/{controller}/{action}/{id}", defaults:New{id =routeparameter.optional}); } }
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
Public Static classWebapiconfig { Public Static voidRegister (httpconfiguration config) {//cross-domain ConfigurationConfig. Enablecors (NewEnablecorsattribute ("*","*","*")); //Web API RoutingCONFIG. Maphttpattributeroutes (); Config. Routes.maphttproute (Name:"Defaultapi", Routetemplate:"Api/{controller}/{action}/{id}", defaults: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;varApiurl = "http://localhost:27221/";$(function() {$.ajax ({type:"Get", Url:apiurl+ "Api/charging/getallchargingdata", data: {}, Success:function(data, status) {if(Status = = "Success") { $("#div_test"). HTML (data); }}, Error:function(e) {$ ("#div_test"). HTML ("Error")); }, Complete: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")] Public classChargingcontroller:apicontroller {/// <summary> ///get all the data/// </summary> /// <returns>Return Data</returns>[HttpGet] Public stringGetallchargingdata () {return "Success"; } }
Iv. 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.
WEBAPI cross-Domain Problem resolution: CORS