Vue.js无法从C# Web API Session获取数据的求助
Vue.js跨域请求C# Web API无法获取Session数据问题排查与解决
问题现象
- 前端Vue.js(运行在
https://localhost:8080)请求C# Web API(https://localhost:7251)的GetUser接口时,返回Session could not retrive user和500内部服务器错误 - 使用Insomnia/Swagger直接测试接口完全正常,登录、注册接口调用无异常
- 仅跨域场景下获取Session数据失败
相关代码
Vue.js请求代码
<script> import axios from "axios"; export default { // eslint-disable-next-line vue/multi-word-component-names name: "Header", data() { return { user: {}, // 默认用户对象为空 }; }, methods: { async getUser() { try { const result = await axios.get( "https://localhost:7251/api/Auths/GetUser", { headers: { "Content-Type": "application/json", }, withCredentials: true, // 启用Session Cookie支持 mode: "cors", // 明确指定为跨域请求 } ); console.log("RESULT: ", result); if (result.status === 200) { console.warn("USER DATA: ", result.data); this.user = result.data; // 假设result.data包含'name'属性 } else { console.error("Failed to fetch user data"); } } catch (error) { console.error( "Error fetching user data:", error.response?.data || error.message ); } }, }, mounted() { this.getUser(); // 组件挂载时调用方法 }, }; </script>
vue.config.js配置
const { defineConfig } = require("@vue/cli-service"); module.exports = defineConfig({ transpileDependencies: true, devServer: { https: true, // 启用HTTPS allowedHosts: "all", }, });
C# Web API Program.cs配置
CORS策略
builder.Services.AddCors(options => { options.AddPolicy("AllowAllOrigins", policy => { policy.WithOrigins("https://localhost:8080")// 前端域名 .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); // 允许传递Cookie/Session }); }); app.UseCors("AllowAllOrigins");
Session配置
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); builder.Services.AddDistributedMemoryCache(); builder.Services.AddSession(options => { options.Cookie.Name = "Session.Works"; options.IdleTimeout = TimeSpan.FromMinutes(30); // Session超时时间 options.Cookie.IsEssential = true; // 即使未授权Cookie也启用Session options.Cookie.SameSite = SameSiteMode.None; // 允许正确传递Cookie //options.Cookie.SecurePolicy = CookieSecurePolicy.Always; options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; });
解决步骤
1. 修正Session中间件注册顺序
在Program.cs中,必须保证app.UseSession()在app.UseCors()之后,且在app.UseAuthorization()和app.MapControllers()之前,错误顺序会导致Session无法绑定到请求上下文:
// 正确顺序示例 app.UseHttpsRedirection(); app.UseCors("AllowAllOrigins"); // 先启用CORS app.UseSession(); // 再启用Session app.UseAuthorization(); app.MapControllers();
2. 调整Cookie安全策略
本地HTTPS环境下,强制设置CookieSecurePolicy.Always,确保Session Cookie仅通过HTTPS传输:
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
3. 简化axios请求配置
移除mode: "cors"(axios跨域时会自动处理,手动设置可能冲突),保留核心的withCredentials: true即可:
<script> import axios from "axios"; export default { name: "Header", data() { return { user: {}, }; }, methods: { async getUser() { try { const result = await axios.get( "https://localhost:7251/api/Auths/GetUser", { withCredentials: true, // 仅保留必要配置 } ); if (result.status === 200) { this.user = result.data; } else { console.error("Failed to fetch user data"); } } catch (error) { console.error( "Error fetching user data:", error.response?.data || error.message ); } }, }, mounted() { this.getUser(); }, }; </script>
4. 验证Session读写逻辑
确保API的GetUser接口正确读取Session,同时登录接口正确写入Session:
// GetUser接口示例 [HttpGet("GetUser")] public IActionResult GetUser() { var userJson = HttpContext.Session.GetString("CurrentUser"); if (string.IsNullOrEmpty(userJson)) { return StatusCode(500, "Session could not retrive user"); } var user = JsonSerializer.Deserialize<User>(userJson); return Ok(user); } // 登录接口示例 [HttpPost("Login")] public IActionResult Login(UserLoginDto dto) { // 省略用户验证逻辑 var validUser = new User { Id = 1, Name = "TestUser" }; // 将用户数据写入Session HttpContext.Session.SetString("CurrentUser", JsonSerializer.Serialize(validUser)); return Ok("Login success"); }
5. 浏览器端验证Cookie传递
打开浏览器开发者工具(F12):
- 在Application标签下,确认
Session.WorksCookie存在,Domain为localhost,Secure属性为true - 在Network标签中,查看
GetUser请求的请求头,确认Cookie字段包含Session.Works=xxx
内容的提问来源于stack exchange,提问作者Hiroco
相关产品推荐
相关产品推荐

