MVC跨域CORS扩展

8 篇文章 0 订阅
7 篇文章 0 订阅

  一般的基于浏览器跨域的主要解决方法有这么几种:1.JSONP       2.IFrame方式    3.通过flash实现  4.CORS跨域资源共享  ,这里我们主要关注的是在MVC里面的CORS跨域,其余的方式大家可以在网上找到相关的知识看一下。

      

  •  CORS的原理:
     CORS定义一种跨域访问的机制,可以让AJAX实现跨域访问。CORS 允许一个域上的网络应用向另一个域提交跨域 AJAX 请求。实现此功能非常简单,只需由服务器发送一个响应标头即可。
      context.HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", origin);
  • CORS浏览器支持情况如下图:
       
     
        也就是说除了IE8以下版本的浏览器不支持,其余的基于W3c标准的大部分都是支持的。
   

一般的针对ASP.NET MVC,cors跨域访问,只需要在web.config中添加如下的内容即可

<system.webServer>

<httpProtocol>

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

</httpProtocol>

<handlers>

<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" />

</handlers>

</system.webServer>

 

但是这种全局设置存在局限性,因为你无法有选择性的设置可以跨域访问你本站的站点,所以就想到能不能通过特性标记控制器,或者标记控制器中的方法来设置跨域访问权限。

比如如下的方式

[ControllerAllowOrigin(AllowSites=new string[] { "aa.com" ,"bb.com"})]

public    class          TestController

     {

  

     }

    这样你可以设置aa.com,bb.com跨域请求你站点TestController里面的任何数据接口方法

   或者是如下方式:

 

public    class          TestController

     {

       [ActionAllowOrigin(AllowSites=new string[] { "aa.com" ,"bb.com"})]

        public   JsonResult   Test()

        {

 

        }

     }

    设置aa.com,bb.com只能跨域请求你站点里面的TestController中的Test方法。

    这样的话,我们控制起来就更加灵活方便,允许跨域访问本站的,在AllowSites里面添加地址就行了。

  1.  基于控制器的跨域访问设置,这边我定义了一个ControllerAllowOriginAttribute,继承于AuthorizeAttribute

  代码如下:

    public class ControllerAllowOriginAttribute : AuthorizeAttribute
    {
        public string[] AllowSites { get; set; }
        public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
        {
            AllowOriginAttribute.onExcute(filterContext, AllowSites);
        }

    }

 

2.基于方法的跨域访问设置,我定义了一个ActionAllowOriginAttribute,继承于ActionFilterAttribute,

  代码如下:

 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 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();
                }
            }
             
        }
    }

其中设置跨域访问权限的代码就是这一段HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", origin);

 

完整的代码如下:

复制代码
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(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();
                }
            }
            

        }
    }

    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 { get; set; }
        public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
        {
            AllowOriginAttribute.onExcute(filterContext, AllowSites);
        }

    }


  
}
复制代码

 

调用方式

  [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);
        }

   }

 

测试的时候,可以将需要跨域访问你本地localhost站点的网站打开,然后F12打开firebug,在console里面输入$.post('http://localhost:80/',{},function(){})或者

$.get('http://localhost:80/',{},function(){})  观察请求状态。

在Java中,我们可以使用CORS(Cross-Origin Resource Sharing)机制来解决跨域问题。CORS是一种机制,允许Web应用程序从不同的域访问其资源。下面是一种使用Spring框架实现CORS的方式: 1. 创建一个类来配置CORS: ``` @Configuration public class CorsConfig { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedHeaders("*"); } }; } } ``` 在上述代码中,我们使用了Spring的@Configuration注解来声明一个Java配置类,然后创建了一个名为CorsConfig的类。该类中我们使用了@Bean注解来声明一个名为corsConfigurer的方法,该方法返回一个WebMvcConfigurer对象。在该方法中,我们使用了WebMvcConfigurerAdapter类来扩展Spring MVC的配置,并重写了addCorsMappings()方法来配置CORS。我们使用了registry.addMapping()方法来配置允许跨域访问的URL和HTTP方法,这里我们设置了允许所有URL("**")和所有HTTP方法(GET、POST、PUT、DELETE、OPTIONS),同时也允许所有请求头。 2. 在Controller中使用@CrossOrigin注解: 我们也可以在Controller中直接使用@CrossOrigin注解来配置CORS,例如: ``` @RestController public class MyController { @CrossOrigin(origins = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE, RequestMethod.OPTIONS}) @GetMapping("/hello") public String hello() { return "Hello World!"; } } ``` 在上述代码中,我们使用了Spring的@RestController注解来声明一个RESTful Controller,并在其中使用了@GetMapping注解来声明一个GET请求的处理方法。在该方法中,我们使用了@CrossOrigin注解来配置CORS,允许所有域名("*")进行跨域访问。 需要注意的是,为了安全起见,应该尽量限制允许跨域访问的域名和方法,避免出现安全问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值