MVC cors Extension across domains

Source: Internet
Author: User
Tags httpcontext

There are a number of major solutions based on browsers across domains: 1. JSONP 2.IFrame mode 3. Realize 4.CORS Cross-domain resource sharing through flash, here we focus on the cors across domains in MVC, the rest of the way you can find relevant knowledge on the Internet to see.

Principle of Cors: Cors defines a cross-domain access mechanism that allows Ajax to implement Cross-domain access. CORS allows network applications on one domain to submit Cross-domain AJAX requests to another domain.       This is a simple function to send a response header to the server. Context. HttpContext.Response.AppendHeader ("Access-control-allow-origin", Origin); The Cors browser support scenario is as follows: that is to say, the rest of the IE8 is supported, except for browsers that are not supported by the following versions.

In general, for ASP.net mvc,cors cross-domain access, just add the following content to the 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 a selective setting to access your site across domains, so it is thought that you can not set Cross-domain access through the attribute tag controller, or the method in the tag controller.

Like the following way

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

public class TestController

{

}

This allows you to set up aa.com,bb.com Cross-domain requests for any data interface method within your site TestController

Or in the following ways:

public class TestController

{

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

Public Jsonresult Test ()

{

}

}

Setup aa.com,bb.com can only request test methods in the TestController in your site across domains.

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

1. Based on the controller's Cross-domain access settings, here I define a controlleralloworiginattribute that inherits 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 Cross-domain access is this section of HttpContext.Response.AppendHeader ("Access-control-allow-origin", Origin);

The complete code is as follows:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;

Using SYSTEM.WEB.MVC; Namespace Ioctest.common {public class Alloworiginattribute {public static void Onexcute (Controllerconte XT 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 ();
        }}} 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); } public class Controlleralloworiginattribute:authorizeattribute {public string[] Allowsites {ge T Set } public override void Onauthorization (System.Web.Mvc.AuthorizationContext filtercontext) {Al
        Loworiginattribute.onexcute (Filtercontext, allowsites); }

    }


  
}

Call 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.

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.