当前位置: 移动技术网 > IT编程>开发语言>c# > .net core web api 添加对session跨域实现

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

2019年10月31日  | 移动技术网IT编程  | 我要评论

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>

 

 

 

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网