MVC跨域CORS扩展

       一般的基于浏览器跨域的主要解决方法有这么几种: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);
        }

    }


  
}
View Code

 

调用方式

  [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(){})  观察请求状态。

 

转载于:https://www.cnblogs.com/a546558309/p/5035471.html

### 如何在PHP中解决CORS问题 #### 设置响应头 为了处理资源共享(CORS)问题,在PHP脚本最开始处设置HTTP响应头是一个常见做法。这可以通过`header()`函数来完成,确保服务器返回适当的Access-Control-Allow-Origin(ACAO)头部。 ```php <?php // 允许所有名访问资源 header("Access-Control-Allow-Origin: *"); // 如果仅限特定名, 替换*为指定URL // header("Access-Control-Allow-Origin: https://example.com"); // 支持的请求方法 header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS"); // 允许携带认证信息(cookie等) header("Access-Control-Allow-Credentials: true"); // 允许的自定义请求头字段 header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With"); ?> ``` 上述代码片段展示了如何配置基本的CORS策略[^1]。对于更复杂的场景,比如当需要对不同路由实施不同的CORS政策时,可以考虑基于框架特性或第三方库来进行管理。 #### 中间件方式(以Laravel为例) 在一个结构化的Web应用里,特别是像Laravel这样的MVC架构下,推荐采用中间件的方式来统一管理和控制CORS行为。创建一个专门用于处理CORS逻辑的中间件,并将其注册到全局或者针对某些特定路由组/控制器上[^4]。 ```php public function handle($request, Closure $next) { // 添加必要的CORS头部 return $next($request)->header('Access-Control-Allow-Origin', '*') ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS') ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization'); } ``` 这种方法不仅使代码更加整洁易维护,而且便于扩展和调整安全策略。 #### 安全性和最佳实践 值得注意的是,在开放API接口的同时也要注意保护系统的安全性。遵循最小权限原则只暴露必需的服务端点;避免过度宽松地使用通配符(*)除非确实有必要;如果启用了凭证共享(`Allow-Credentials`)则不允许将Origin设为通配符[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值