解决方案:
1、针对ASP.NET MVC和ASP.NET Web API两种项目类型,我做了一些研究,确定下面的方案是可行的。
针对ASP.NET MVC,只需要在web.config中添加如下的内容即可
1 <system.webServer> 2 3 <httpProtocol> 4 5 <customHeaders> 6 7 <add name="Access-Control-Allow-Origin" value="*" /> 8 9 <add name="Access-Control-Allow-Headers" value="Content-Type" /> 10 11 <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" /> 12 13 </customHeaders> 14 15 </httpProtocol> 16 17 <handlers> 18 19 <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> 20 21 <remove name="OPTIONSVerbHandler" /> 22 23 <remove name="TRACEVerbHandler" /> 24 25 <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> 26 27 </handlers> 28 29 </system.webServer>
2、建立Filters,cors
1 public class CorsAttribute : ActionFilterAttribute, IActionFilter 2 { 3 public override void OnResultExecuted(ResultExecutedContext filterContext) 4 { 5 try 6 { 7 base.OnResultExecuted(filterContext); 8 HttpContext.Current.Response.Headers.Add("Access-Control-Allow-Origin", "*"); 9 HttpContext.Current.Response.Headers.Add("Access-Control-Allow-Headers", "x-requested-with,content-type,requesttype,Token"); 10 HttpContext.Current.Response.Headers.Add("Access-Control-Allow-Methods", "POST,GET"); 11 } 12 catch (Exception ex) 13 { 14 15 } 16 } 17 }
页面调用:
1 [Filters.Cors] 2 public ActionResult Index() 3 { 4 return view(); 5 }