zoukankan      html  css  js  c++  java
  • c# MCV 实现跨域

    前言

    core跨域严格来说是要分为两步的,因为分为简单跨域和复杂跨域,第一种为直接允许跨域,第二种因为存在某些框架本身不允许put,delete这两个,那么这就是一个问题了。对的,那么mvc这种重量级框架,肯定是帮我们封装好了。

    正文

    我们可以在配置文件中配置允许put和delete,然后设定运行的origin。

    <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> 
    

    当然我们也可以通过过滤器来过滤:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace IocTEST.Common
    {
        public class AllowOriginAttribute
        {
            public static void onExcute(ControllerContext context, string[] AllowSites)
            {
                var origin = context.HttpContext.Request.Headers["Origin"];
                Action action = () =>
                {
                    context.HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", origin);
    
                };
                if (AllowSites != null && AllowSites.Any())
                {
                    if (AllowSites.Contains(origin))
                    {
                        action();
                    }
                }
            }
        }
    
        public class ActionAllowOriginAttribute : ActionFilterAttribute
        {
            public string[] AllowSites { get; set; }
            public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
            {
                AllowOriginAttribute.onExcute(filterContext, AllowSites);
                base.OnActionExecuting(filterContext);
            }
        }
        public class ControllerAllowOriginAttribute : AuthorizeAttribute
        {
            public string[] AllowSites { get; set; }
            public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
            {
                AllowOriginAttribute.onExcute(filterContext, AllowSites);
            }
        }
    }
    

    总结

    这些其实都是mvc 帮我们封装好了的,那么如何自己手写呢?晚点发布。

  • 相关阅读:
    U盘安装WIN10专业版
    jquery template模版引擎
    MySQL大数据量快速分页实现(转载)
    MySQL for Windows 解压缩版安装 和 多实例安装
    macbook 重装win7
    MySQL for Visual Studio Version
    VS2010中没有ado.net entity data model实体数据模型这一选项-解决办法
    修改server 2008远程桌面端口
    懒加载
    html-css 常用
  • 原文地址:https://www.cnblogs.com/aoximin/p/13035902.html
Copyright © 2011-2022 走看看