配置跨域同源策略 WebApi模式+MVC模式两种

WebApi:
https://www.cnblogs.com/hnsongbiao/p/9375997.html
https://blog.csdn.net/weixin_43803985/article/details/103342500

MVC:
1.C# 配置
通用模式:Web.config

  <system.webServer>
......
	  <!--httpProtocol姜佳泉为React配置同源策略-->
	  <!--<httpProtocol>
		  <customHeaders>
			  <add name="Access-Control-Allow-Origin" value="http://localhost:3000" />
			  <add name="Access-Control-Allow-Headers" value="Content-Type" />
			  <add name="Access-Control-Allow-Credentials" value="true" />
			  <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE" />

		  </customHeaders>
	  </httpProtocol>-->
  ......
  </system.webServer>

2.Filter定向配置
新增一个过滤器


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace BP020439.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);
                context.HttpContext.Response.AppendHeader("Access-Control-Allow-Credentials", "true");
                context.HttpContext.Response.AppendHeader("Access-Control-Allow-Headers", "Content-Type");

            };
            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);
        }

    }



}

使用该过滤器
[ControllerAllowOrigin(AllowSites = new string[] { "http://localhost:3000" })]//不得用*,必须指定源

PS:附上fetch


 fetch('http://localhost:29717/S_USER/test',
          {
              headers: {
                  'content-type': 'application/json',
              },
              method: 'POST', // // *GET, POST, PUT, DELETE, 等.
              mode: 'cors',!!!!!!!!!!!!!!!!!!!
              body: JSON.stringify({//请求携带的参数信息
                  messagesion: JSON.stringify(this.props.messagesion),
                  current: this.state.current,
              }),
              credentials: 'include', // include(始终携带cookie), *same-origin(cookie同源携带), omit(不携带)!!!!!!!!!!!!!!!!!!!!!!!!!!!!
          }
      ).then(
          response => {
              if (response.ok) {//如果返回的response是健康的,ok的
                  return response.json()//则json序列化成数组
              } else {
                  return Promise.reject({//否则利用Promise.reject将sick的response赋值给sick_response
                      //并携带sick_response跳过第二个.then进入.catch
                      sick_response: response
                  })
              }
          }
      ).then(
          data => {
              this.setState({
                  datasource: JSON.parse(data.dtjson),
                  total: data.total,
              })
          }
      ).catch(//sick_response进入此处进行请求失败反馈
          sick_response => {
              console.log(sick_response)
          }
      )
  }


拦截fetch技巧

!!!!!


 public class UserFilter: ActionFilterAttribute
    {

        public override void OnActionExecuting(ActionExecutingContext con)
        {

            if (con.HttpContext.Session["sysUser"] == null || con.HttpContext.Session["sysUser"].ToString() == "")
            {
                // con.Result = Content("<script type='text/javascript'>top.location = '/login';</script>");

                con.HttpContext.Response.Write("<script type='text/javascript'>top.location = '/Login/Index';</script>");
                con.Result = new EmptyResult();!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                // con.HttpContext.Response.Redirect("/Login/Index");
            }

        }

    }

posted @ 2020-07-31 10:50  姜佳泉  阅读(225)  评论(0编辑  收藏  举报