我在客户端有以下代码:
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 的早期(非核心)版本中工作。
您需要在获取中设置凭据选项,这将执行以下操作:
Request 接口的凭据只读属性指示在跨源请求的情况下用户代理是否应从其他域发送 cookie。这类似于 XHR 的 withCredentials 标志,但具有三个可用值(而不是两个)
-
omit
:切勿发送 cookie。
-
same-origin
:如果 URL 与调用脚本同源,则发送用户凭据(cookie、基本 http 身份验证等)。这是默认值。
-
include
:始终发送用户凭据(cookie、基本 http 身份验证等),即使是跨源调用。
Source https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials
您的获取现在如下所示:
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));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)