WEBAPI cross-Domain Problem resolution: CORS

Source: Internet
Author: User

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

Index.js file

var apiurl = "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 class Chargingcontroller:apicontroller {//<summary>///For        all data//        </summary> ///        <returns> return Data </returns>        [HttpGet]        public string Getallchargingdata ()        {            return ' Success ';        }    }

The routing rules for configuring WEBAPI are called through action. WebApiConfig.cs file

public static class Webapiconfig    {public        static void Register (httpconfiguration config)        {            //Web API Routing            CONFIG. 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 class Webapiconfig    {public        static void Register (httpconfiguration config)        {            //cross-domain Configuration            CONFIG. Enablecors (New Enablecorsattribute ("*", "*", "*"));            Web API Routing            config. 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;var Apiurl = "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 class Chargingcontroller:apicontroller {//<summary>///For        all data//        </summary> ///        <returns> return Data </returns>        [HttpGet]        public string Getallchargingdata ()        {            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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.