MVC cross-domain cors extension

Source: Internet
Author: User
Tags httpcontext

General browser-based cross-domain main solutions are the following: 1. JSONP 2.IFrame mode 3. Realize 4.CORS cross-domain resource sharing through flash, here we mainly focus on the Cors cross-domain in MVC, the rest of the way you can find relevant knowledge on the Internet to see.

    • The principle of cors:
Cors defines a mechanism for cross-domain access that enables AJAX to be accessed across domains. CORS allows a network application on one domain to submit cross-domain AJAX requests to another domain.      This is very simple to implement, and only one response header is sent by the server. Context. HttpContext.Response.AppendHeader ("Access-control-allow-origin", Origin);
    • Cors Browser support scenarios such as:
This means that in addition to IE8 the following versions of browsers are not supported, the rest of the web-based standards are mostly supported.

In general, cross-domain access for ASP. NET Mvc,cors, just add the following in Web. config

<system.webServer>

<customHeaders>

<add name= "Access-control-allow-origin" value= "*"/>

<add name= "Access-control-allow-headers" value= "Content-type"/>

<add name= "Access-control-allow-methods" value= "GET, POST, PUT, DELETE, OPTIONS"/>

</customHeaders>

<remove name= "extensionlessurlhandler-integrated-4.0"/>

<remove name= "Optionsverbhandler"/>

<remove name= "Traceverbhandler"/>

<add name= "extensionlessurlhandler-integrated-4.0" path= "*." verb= "*" type= " System.Web.Handlers.TransferRequestHandler "precondition=" integratedmode,runtimeversionv4.0 "/>

</system.webServer>

However, this global setting has limitations because you cannot have selective settings that can access your site on a cross-domain, so you can expect to be able to set cross-domain access by using the attribute tag controller, or by tagging a method in the controller.

such as the following way

[Controlleralloworigin (Allowsites=new string[] {"aa.com", "bb.com"})]

public class TestController

{

}

This allows you to set aa.com,bb.com cross-domain request any data interface method inside your site TestController

Or in the following ways:

public class TestController

{

[Actionalloworigin (Allowsites=new string[] {"aa.com", "bb.com"})]

Public Jsonresult Test ()

{

}

}

Setting aa.com,bb.com can only cross-domain request the test method in the TestController inside your site.

In this way, we control more flexible and convenient, allowing cross-domain access to the site, in the Allowsites add the address on the line.

1. Controller-based cross-domain access settings Here I define a controlleralloworiginattribute, inherited from Authorizeattribute

The code is as follows:

public class Controlleralloworiginattribute:authorizeattribute
{
Public string[] Allowsites {get; set;}
public override void Onauthorization (System.Web.Mvc.AuthorizationContext filtercontext)
{
Alloworiginattribute.onexcute (Filtercontext, allowsites);
}

}

2. Method-based cross-domain access settings, I defined a actionalloworiginattribute, inherited from ActionFilterAttribute,

The code is as follows:

public class Actionalloworiginattribute:actionfilterattribute
{
Public string[] Allowsites {get; set;}
public override void OnActionExecuting (System.Web.Mvc.ActionExecutingContext filtercontext)
{
Alloworiginattribute.onexcute (Filtercontext, allowsites);
Base. OnActionExecuting (Filtercontext);
}
}

The core code is actually very simple, just a few lines:

public class Alloworiginattribute
{
public static void Onexcute (ControllerContext context, string[] allowsites)
{
var origin = context. httpcontext.request.headers["Origin"];
Action action = () =
{
Context. HttpContext.Response.AppendHeader ("Access-control-allow-origin", Origin);

};
if (allowsites! = null && allowsites.any ())
{
if (Allowsites.contains (Origin))
{
Action ();
}
}

}
}

The code that sets the cross-domain access permission is this section of HttpContext.Response.AppendHeader ("Access-control-allow-origin", Origin);

The complete code is as follows:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;usingSYSTEM.WEB.MVC;namespaceioctest.common{ Public classAlloworiginattribute { Public Static voidOnexcute (ControllerContext context,string[] allowsites) { varOrigin = context. httpcontext.request.headers["Origin"]; Action Action= () + ={context. HttpContext.Response.AppendHeader ("Access-control-allow-origin", origin); }; if(Allowsites! =NULL&&Allowsites.any ()) { if(Allowsites.contains (Origin)) {action (); } } Else{action (); } } }  Public classActionalloworiginattribute:actionfilterattribute { Public string[] Allowsites {Get;Set; }  Public Override voidonactionexecuting (System.Web.Mvc.ActionExecutingContext filtercontext) {Alloworiginattribute.onex Cute (filtercontext, allowsites); Base. OnActionExecuting (Filtercontext); } }  Public classControlleralloworiginattribute:authorizeattribute { Public string[] Allowsites {Get;Set; }  Public Override voidonauthorization (System.Web.Mvc.AuthorizationContext filtercontext) {Alloworiginattribute.onexcute ( Filtercontext, allowsites); } } }
View Code


Invocation mode

[Controlleralloworigin (allowsites = new string[] {"http://www.cnblogs.com"})]
public class Homecontroller:controller
{


Public Jsonresult Test ()
{
Return Json (New {name = "AAA"}, Jsonrequestbehavior.allowget);
}

}

public class Homecontroller:controller
{

[Actionalloworigin (allowsites = new string[] {"http://www.cnbeta.com"})]
Public Jsonresult Test ()
{
Return Json (New {name = "AAA"}, Jsonrequestbehavior.allowget);
}

}

When testing, you can open a Web site that requires cross-domain access to your local localhost site, and then F12 open Firebug, enter $.post (' http://localhost:80/', {},function () {}) in the console, or

$.get (' http://localhost:80/', {},function () {}) observes the request status.

MVC cross-domain cors extension

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.