MVC跨域CORS扩展
CORS的原理:
针对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>
但是这种全局设置存在局限性,因为你无法有选择性的设置可以跨域访问你本站的站点,所以就想到能不能通过特性标记控制器,或者标记控制器中的方法来设置跨域访问权限。
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.Mvc; 6 7 namespace IocTEST.Common 8 { 9 public class AllowOriginAttribute 10 { 11 public static void onExcute(ControllerContext context, string[] AllowSites) 12 { 13 var origin = context.HttpContext.Request.Headers["Origin"]; 14 Action action = () => 15 { 16 context.HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", origin); 17 18 }; 19 if (AllowSites != null && AllowSites.Any()) 20 { 21 if (AllowSites.Contains(origin)) 22 { 23 action(); 24 } 25 } 26 27 28 } 29 } 30 31 public class ActionAllowOriginAttribute : ActionFilterAttribute 32 { 33 public string[] AllowSites { get; set; } 34 public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) 35 { 36 AllowOriginAttribute.onExcute(filterContext, AllowSites); 37 base.OnActionExecuting(filterContext); 38 } 39 } 40 public class ControllerAllowOriginAttribute : AuthorizeAttribute 41 { 42 public string[] AllowSites { get; set; } 43 public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext) 44 { 45 AllowOriginAttribute.onExcute(filterContext, AllowSites); 46 } 47 48 } 49 50 51 52 }
1 [ControllerAllowOrigin(AllowSites = new string[] { "http://www.cnblogs.com" })] 2 public class HomeController : Controller 3 { 4 5 6 public JsonResult Test() 7 { 8 return Json(new { name = "aaa" }, JsonRequestBehavior.AllowGet); 9 } 10 11 } 12 13 14 15 16 17 public class HomeController : Controller 18 { 19 20 [ActionAllowOrigin(AllowSites = new string[] { "http://www.cnbeta.com" })] 21 public JsonResult Test() 22 { 23 return Json(new { name = "aaa" }, JsonRequestBehavior.AllowGet); 24 } 25 26 }
测试的时候,可以将需要跨域访问你本地localhost站点的网站打开,然后F12打开firebug,在console里面输入$.post('http://localhost:80/',{},function(){})或者
$.get('http://localhost:80/',{},function(){}) 观察请求状态。