我在客户端有以下代码:fetch("/music/index", { headers: { "Content-Type": "application/json" } }) .then(response => { if (!response.ok) { throw response; } return response.json(); }) .then(json => { console.log("Done! It's all good"); }) .catch(response => console.log(response));不幸的是,这甚至没有到达MusicController(服务器端),它看起来如下(为了说明这一点而进行了简化):[Authorize]public class MusicController : Controller { public async Task<IActionResult> Index() { IEnumerable<Song> songs = await _songsRepository.GetAll(); return Json(songs); }}从我在开发者控制台中看到的我被重定向到 /Account/Login?returnUrl...同时,使用 jquery api,一切似乎都正常:$.get("/music/index") .done(json => console.log("Done! It's all good")) .fail(error => console.log(error));我怀疑我没有正确设置我的标题?不确定在网上找不到任何东西。此外,此(或非常相似)代码用于在以前(非核心)版本的 ASP.NET 中工作。
1 回答

慕莱坞森
TA贡献1810条经验 获得超4个赞
您需要在提取中设置凭据选项,这将执行以下操作:
Request 接口的凭据只读属性指示用户代理是否应该在跨域请求的情况下发送来自其他域的 cookie。这类似于 XHR 的 withCredentials 标志,但具有三个可用值(而不是两个)
omit
: 永远不要发送cookies。
same-origin
:如果 URL 与调用脚本来自同一来源,则发送用户凭据(cookie、基本 http 身份验证等)。这是默认值。
include
:始终发送用户凭据(cookies、基本的 http 身份验证等),即使是跨域调用。
你的 fetch 现在看起来像这样:
fetch("/music/index", {
headers: { "Content-Type": "application/json" },
credentials: 'include'
})
.then(response => {
if (!response.ok) {
throw response;
}
return response.json();
})
.then(json => {
console.log("Done! It's all good");
})
.catch(response => console.log(response));
添加回答
举报
0/150
提交
取消