zoukankan      html  css  js  c++  java
  • aspnet mvc 中 跨域请求的处理方法

      ASP.NET 处理跨域的两种方式

         方式1,后端程序处理。原理:给响应头加上允许的域即可,*表示允许所有的域

                    定义一个cors的过滤器

    加在在action或者controller上面即可

     具体代码:

    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.All, Inherited = true, AllowMultiple = true)]
    public class CorsAttribute : ActionFilterAttribute, IActionFilter
    {
    
    
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
          try
          {
            base.OnResultExecuted(filterContext);
    
    
            HttpContext.Current.Response.Headers.Add("Access-Control-Allow-Origin", "*");
            HttpContext.Current.Response.Headers.Add("Access-Control-Allow-Headers", "x-requested-with,content-type,requesttype,Token");
            HttpContext.Current.Response.Headers.Add("Access-Control-Allow-Methods", "POST,GET");
    
          }
          catch (Exception exception)
          {
          }
      }
    
    }
    

      

     方式2(IIS处理):(推荐)最简单的处理方式, 原理和上面相同,只不过是由IIS来实现,操作也很简单。修改web.config文件即可。

    找到system.WebServer节点下面添加以下即可

     

    <httpProtocol>
    <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="*" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE" />
    </customHeaders>
    </httpProtocol>
    
     
    

      

  • 相关阅读:
    哈希算法是怎么实现的
    高并发下日志组件的各种实现方式
    算法是如何影响程序编码方式的
    <<.NET B/S 架构实践>> 几种概念区别
    如何扩大系统盘空间
    区别:ASP.NET MVC的Model、DTO、Command
    能递归检查DataAnnotations的验证函数
    NuGet的本地服务器安装与Package的发布(呕吐)
    多模块分布式系统的简单服务访问
    多模块后带来的问题解决方法
  • 原文地址:https://www.cnblogs.com/jimsfriend/p/9253266.html
Copyright © 2011-2022 走看看