欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.net core web api 添加对session跨域实现

程序员文章站 2023-10-30 23:43:16
1.配置Startup 2.控制器启用 3.Ajax异步跨域调用 ......

1.配置startup

/configureservices添加:

services.addsession(options =>
            {
                options.cookie.name = ".adventureworks.session";
                options.idletimeout = system.timespan.fromseconds(120);//设置session的过期时间
                options.cookie.httponly = true;//设置在浏览器不能通过js获得该cookie的值
            });
            services.tryaddsingleton<ihttpcontextaccessor, httpcontextaccessor>();
            services.addhttpcontextaccessor();
            #region 跨域
            services.addcors(options =>
            options.addpolicy("allowsamedomain",
            builder => builder.withorigins().allowanymethod().allowanyheader().allowanyorigin().allowcredentials()));
            #endregion
//configure添加:
app.usecookiepolicy();
app.usesession();

2.控制器启用

[enablecors("allowsamedomain")]

3.ajax异步跨域调用

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title></title>
    <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/1.8.3/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
    <script type="text/javascript">
        $.ajax({  //ajax post方式调用webapi
            type: "post",
            contenttype: 'application/json',
            url: 'http://192.168.84.170:9005/api/adminmanager/login',
            data:json.stringify({ account: "admin", passwd: "e10adc3949ba59abbe56e057f20f883e" }),
            datatype: 'json',
        xhrfields: { withcredentials: true },
            success: function (data) {
                alert(data.msg);
                console.log(data);
            },
            error: function (xhr) {
                console.log(xhr.responsetext);
            }
        })
    </script>
</head>
<body>
</body>
</html>