VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > c#教程 >
  • C#教程之.net core web api 添加对session跨域实现

本站最新发布   C#从入门到精通
试听地址  
https://www.xin3721.com/eschool/CSharpxin3721/

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>
复制代码

相关教程