C # webapi Troubleshooting cross-domain issues: Cors

Source: Internet
Author: User

What are cross-domain issues

For security reasons, the browser restricts cross-site requests originating in the script, and the browser requires JavaScript or cookies to access only the content in the same domain. For this reason, data access between our different sites is denied.

Cors solves cross-domain issues

The cross-domain resource sharing (CORS) mechanism allows the WEB application server to control cross-domain access, allowing cross-domain data transfer to be secured. 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.

Resolving cross-domain problem instances

Here's a simple example of how to use cors to solve cross-domain

1. Establish test project

1.1. Create a new two ASP. NET Web application as a Web site and Webapi site:

1.2. Configure WEBAPI Site
Configure the Web API route in the WebApiConfig.cs file to point to the specific action

//Web API 路由config.MapHttpAttributeRoutes();config.Routes.MapHttpRoute(    name: "DefaultApi1", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional });

Create a new test method in the controller to return the requested data:

[authorize][routeprefix ( "Api/account")]public class accountcontroller:apicontroller{///<summary> ///get all data ///</summary> ///<returns> return data </returns > [HttpGet] public string  Getalldata () {return  "Success";}}      

Start the Web API project with a site port number of: 8476

1.3. Configure the Web site
Create a new index test page:

<Html><Head><MetaName="Viewport"Content="Width=device-width"/><title>index</ title> <script src=" ~/scripts/jquery-1.10.2.min.js ">< Span class= "Hljs-tag" ></script></ head><body> test Result: <div id=" Div_test " > Hello World </div></body></HTML>     
public ActionResult Index(){    return View();}

Using jquery's AJAX processing requests:

<Script>    var Apiurl ="http://localhost:8476/"; $(function  () {$.ajax ({type:  "get", Datatype: "json", Url:apiurl +  "Api/account/getalldata", data: {} , success: function  (data, status {if (data =  "Success") {$ ( "#div_ Test "). HTML (data); }}, Error: function  (E) {$ ( "#div_test"). HTML ( "Error");}, complete: function  () {});}); </SCRIPT>         
2. Testing

To run the Web project without doing any processing, the result is:

You can see that the browser has denied our cross-domain access.

3. Using cors Across Domains

Install Cors First, use NuGet to search for "microsoft.aspnet.webapi.cors" on the Webapicors project, install the first

When we install this package, the existing packages directory will add two names "microsoft.aspnet.cors.5.2.3" and "microsoft.aspnet.webapi.cors.5.2.3", respectively. References to the two assemblies saved (System.Web.Cors.dll and System.Web.Http.Cors.dll) are automatically added to the Webapicors project

Then configure the cross-domain in the WebApiConfig.cs folder under the App_start folder

public Span class= "Hljs-keyword" >static class webapiconfig{public Span class= "Hljs-keyword" >static void register ( Httpconfiguration config) {//cross-domain configuration config. Enablecors (new enablecorsattribute ( "*",  "*"); //Web API Route CONFIG. Maphttpattributeroutes (); Config. Routes.maphttproute (name:  "DefaultApi1", 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 the following introduction

Re-run:
Google

IE7, IE8, IE9

I have set the cross-domain, how IE7, 8, 9 or not? This time it is necessary to talk about Cors browser support issues. This map can be found all over the Web:

Can see IE8, 9 only some browser support, then how to solve the IE browser support problem, in fact, at the call to specify jQuery.support.cors = true; This sentence will solve the problem of IE8, 9:

<Script>JQuery.support.cors =Truevar Apiurl ="http://localhost:8476/"; $(function  () {$.ajax ({type:  "get", Url:apiurl +  "Api/account/getalldata", data: {}, Success: function  (data, status) {if (status = = " #div_test "). HTML ( data); }}, Error: function  (E) {$ ( "#div_test"). HTML ( "Error");}, complete: function  () {});}); </SCRIPT>         

4, the specific parameters of cors settings.

Here's what we used: CONFIG. Enablecors (New Enablecorsattribute ("," "," * ")), the * number here means that any request can return a resource if someone knows your URL, which is not secure and therefore requires access control.
Configuration Method One
In the Web. config configuration:

<appSettings>  <add key="cors:allowedMethods" value="*"/>  <add key="cors:allowedOrigin" value="http://localhost:8610"/> <add key="cors:allowedHeaders" value="*"/></appSettings>

Then in the WebApiConfig.cs file configuration

Publicstatic void Register (httpconfiguration config) { //cross-domain config var allowedmethods = Configuration manager.appsettings["Cors:allowedmethods"]; var allowedorigin = configurationmanager.appsettings["Cors:allowedorigin"]; var allowedheaders = configurationmanager.appsettings["Cors:allowedheaders"]; var geducors = New Enablecorsattribute (Allowedorigin, Allowedheaders, allowedmethods) {supportscredentials = true}; Config. Enablecors (geducors); //config. Enablecors (New Enablecorsattribute ("*", "*", "*"));             

Configuration Method Two
If you only want to cross-domain some APIs, you can use attribute annotations directly on the API's classes.

[Enablecors (Origins:"Http://localhost:8610/", headers: "Get,post,put,delete")] public class accountcontroller:apicontroller{///<summary> ///get all data ///</summary> ///<returns> return data </returns > [HttpGet] public string  Getalldata () {return  "Success";}}      

C # webapi Troubleshooting cross-domain issues: Cors

Related Article

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.