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

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>

 

 

 

 

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

全文结束