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

原文地址:https://www.cnblogs.com/aoximin/p/13035902.html