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 帮我们封装好了的,那么如何自己手写呢?晚点发布。

  • 相关阅读:
    PostBUILD Event Command Line
    vue 中 $set与$delete的使用
    前端动画必知必会:React 和 Vue 都在用的 FLIP 思想实战
    根据JSON自动构建的vue筛选框组件
    手摸手带你理解Vue的Computed原理
    Flutter开发初探
    实战技巧,Vue原来还可以这样写
    你应该知道的Vue高级特性
    如何去除vue项目中的console内容
    vue: 组件之间传值
  • 原文地址:https://www.cnblogs.com/aoximin/p/13035902.html
Copyright © 2011-2022 走看看