You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用IdentityServer4的ASP.NET Core MVC中Ajax POST重定向异常排查

解决Fetch API POST请求被IdentityServer重定向的问题

你遇到的核心问题是Fetch API默认不会自动携带认证Cookie,而ASP.NET Core的Cookie认证机制依赖这些Cookie识别已登录用户。相比之下,jQuery的$.ajax在跨域场景下默认配置了携带凭证的选项,所以能正常工作。下面是具体的解决方案:

1. 给Fetch请求添加credentials: 'include'配置

这是最关键的一步,告诉Fetch在请求时携带包含认证信息的Cookie(无论同域还是跨域请求)。示例代码如下:

// 假设你要POST的JSON数据
const postData = { /* 你的业务数据结构 */ };

fetch('/YourController/Update', {
  method: 'POST',
  credentials: 'include', // 必须添加这个选项
  headers: {
    'Content-Type': 'application/json', // 根据数据格式调整,表单数据用application/x-www-form-urlencoded
  },
  body: JSON.stringify(postData)
})
.then(async response => {
  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`请求失败: ${errorText}`);
  }
  return response.json(); // 按实际响应格式处理
})
.then(data => {
  console.log('更新成功:', data);
})
.catch(error => {
  console.error('请求出错:', error);
});

2. 确认CORS配置允许携带凭证

你已经开启了CORS,但需要确保配置中包含AllowCredentials(),并且不能用通配符*作为允许的源,必须指定主应用的具体域名/端口。修改Startup.cs中的CORS配置:

services.AddCors(options =>
{
    options.AddPolicy("AllowAppOrigin",
        builder => builder.WithOrigins("http://localhost:你的主应用端口") // 替换成你的主应用地址
                          .AllowAnyMethod()
                          .AllowAnyHeader()
                          .AllowCredentials()); // 必须添加这一行
});

// 在Configure方法中,确保CORS中间件在认证中间件之前(跨域场景下)
app.UseCors("AllowAppOrigin");
app.UseAuthentication();
app.UseAuthorization();

为什么jQuery Ajax能正常工作?

jQuery的$.ajax在跨域请求时,默认会设置xhrFields: { withCredentials: true },同域请求时也会自动携带Cookie,所以能通过服务器的认证校验。而Fetch API为了遵循更严格的安全默认,需要手动开启凭证携带。

额外检查项

  • 确认请求的Content-Type与服务器端接收格式匹配(比如用[FromBody]接收JSON,就必须设置Content-Type: application/json)。
  • 查看浏览器控制台是否有CORS相关错误,这能帮你快速定位配置问题。

按照以上步骤调整后,你的Fetch POST请求应该就能正常触发带[Authorize]特性的控制器动作,并且能正确获取User.Identity.Claims了。

内容的提问来源于stack exchange,提问作者keitn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:19:41