• .NET 跨域问题


    解决方案:

    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     }
    View Code

    页面调用:

    1 [Filters.Cors]
    2 public ActionResult Index()
    3 {
    4       return view();  
    5 }
  • 相关阅读:
    git stash错误小记
    PHP,Mysql根据经纬度计算距离并排序
    JS~字符串长度判断,超出进行自动截取(支持中文)
    Redis的三种启动方式
    Ubuntu 14.04 LTS下安装Google Chrome浏览器
    PHP-PHPExcel用法详解
    git设置log的别名 for hist log样式格式化
    Ubuntu系统下配置PHP支持SQLServer 2005
    Git命令图片版
    《一线架构师实践指南》读后感(二)
  • 原文地址:https://www.cnblogs.com/bangguo/p/13112285.html
Copyright © 2020-2023  润新知