C# 跨域 請求帶cookie


原文:https://blog.csdn.net/z69183787/article/details/78954325

 

背景:

  別個的項目,要開發App接口,要求用前端AJAX的方式訪問接口數據。

  后台項目用的asp.net mvc,但是所有的方法都是寫在controller層里面的,

  App接口要求的功能大部分都是controller層里面的方法,

  肯定不可能再重新寫一遍接口咯,時間也來不及,並且方法也會重復,不利於維護。

  

 

主要做了兩點:

  1、讓后端支持跨域

  2、跨域時附帶把cookie傳過去

 

這里有一個坑,特別注意哈!!!:服務器端 Access-Control-Allow-Credentials = true時,參數Access-Control-Allow-Origin 的值不能為 '*' 。

 

跨域的代碼:

后端:

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

namespace CLBIM.Filter
{
    /// <summary>
    /// 運行跨域
    /// </summary>
    public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
    {
        private string[] _domains;

        public AllowCrossSiteJsonAttribute()
        {
            _domains = new string[] { };
        }
        public AllowCrossSiteJsonAttribute(string domain)
        {
            _domains = new string[] { domain };
        }
        public AllowCrossSiteJsonAttribute(string[] domains)
        {
            _domains = domains;
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //var context = filterContext.RequestContext.HttpContext;
            //var host = context.Request.UrlReferrer?.Host;
            //if (host != null && _domains.Contains(host))
            //{
            //    filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
            //}


            //服務器端 Access-Control-Allow-Credentials = true時,參數Access-Control-Allow-Origin 的值不能為 '*' 。
            var Origin = filterContext.RequestContext.HttpContext.Request.Headers["Origin"];
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", Origin);
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Credentials", "true");
            base.OnActionExecuting(filterContext);
        }
    }
}
View Code

 

前端:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <meta charset="utf-8" />
    <style type="text/css">
        input {
            width: 200px;
            margin: 5px;
            height: 30px;
        }
    </style>
    <script src="http://libs.baidu.com/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
</head>
<body>

    <div id="div1"></div>



    <script type="text/javascript">

        var url = 'http://192.168.2.73:9012';//遠程服務地址
        url = 'http://183.66.231.18:8050';



        //帶cookie的方式
        //查看返回的數據:F12 -> Network -> XHR -> 點開一個具體的請求 -> Preview

        //登錄
        function fn1() {
            var model = {
                UserName: "admin",
                Password: "123456",
            };
            $.ajax({
                type: "POST",
                url: url + "/Login/VerifyLogin",
                data: model,
                dataType: 'json',
                xhrFields: {
                    withCredentials: true
                },
                crossDomain: true,
                success: function (response) {
                    console.log(response);//返回的內容
                }
            });
        }

        //退出登錄
        function fn2() {
            $.ajax({
                type: "POST",
                url: url + "/Login/LogOut",
                dataType: 'json',
                xhrFields: {
                    withCredentials: true
                },
                crossDomain: true,
                success: function (response) {
                    console.log(response);
                }
            });
        }

        //獲取菜單
        function fn3() {
            $.ajax({
                type: "POST",
                url: url + "/SystemManage/Menu/GetAllMenu",
                dataType: 'json',
                xhrFields: {
                    withCredentials: true
                },
                crossDomain: true,
                success: function (response) {
                    console.log(response);
                }
            });
        }


        
        //生成按鈕

        var fn_names = [];
        fn_names.push("帶cookie-登錄");
        fn_names.push("帶cookie-退出登錄");
        fn_names.push("帶cookie-獲取菜單");

        var CreateHtml = function () {
            var strHtml = '';
            for (var i = 0; i < fn_names.length; i++) {
                var num = i + 1;
                var name = fn_names[i];
                strHtml += '<input type="button" value="fn' + num + '  ' + name + '" onclick="fn' + num + '()" />';
            }
            $("#div1").html(strHtml);
        }();


    </script>

</body>
</html>
View Code

 

注意一下ajax的配置參數:

        function fn1() {
            var model = {
                UserName: "admin",
                Password: "123456",
            };
            $.ajax({
                type: "POST",
                url: url + "/Login/VerifyLogin",
                data: model,
                dataType: 'json',
                xhrFields: {
                    withCredentials: true
                },
                crossDomain: true,
                success: function (response) {
                    console.log(response);//返回的內容
                }
            });
        }

 

后端主要代碼:

 var Origin = filterContext.RequestContext.HttpContext.Request.Headers["Origin"];
 filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", Origin);
 filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Credentials", "true");

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM