• 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节点下面添加以下即可

    具体代码:

    1 <httpProtocol>
    2 <customHeaders>
    3 <add name="Access-Control-Allow-Origin" value="*" />
    4 <add name="Access-Control-Allow-Headers" value="*" />
    5 <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE" />
    6 </customHeaders>
    7 </httpProtocol>
  • 相关阅读:
    systick运用
    stm32的systick原理与应用
    PID算法知识点博文收藏记录
    关于STM32驱动DS1302实时时钟的一点思考
    什么是同步?什么是互斥?
    C语言小笔记(1)
    typedef 复杂函数指针
    获取窗口句柄
    GetWindowRect和GetClientRect的区别详解
    RepositionBars的用法和参数的意义(引用别人的)
  • 原文地址:https://www.cnblogs.com/wahson2019/p/10861161.html
Copyright © 2020-2023  润新知