JS Fetch API 不适用于具有 Authorize 属性的 ASP.NET Core 2 控制器

Dim*_*rov 3 javascript c# jquery asp.net-core asp.net-core-2.0

我在客户端有以下代码:

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));
Run Code Online (Sandbox Code Playgroud)

不幸的是,这甚至没有到达MusicController(服务器端),它看起来如下(为了说明这一点而进行了简化):

[Authorize]
public class MusicController : Controller {
    public async Task<IActionResult> Index() {        
        IEnumerable<Song> songs = await _songsRepository.GetAll();
        return Json(songs);
    }
}
Run Code Online (Sandbox Code Playgroud)

从我在开发者控制台中看到的我被重定向到 /Account/Login?returnUrl...

同时,使用 jquery api,一切似乎都正常:

$.get("/music/index")
    .done(json => console.log("Done! It's all good"))
    .fail(error => console.log(error));
Run Code Online (Sandbox Code Playgroud)

我怀疑我没有正确设置我的标题?不确定在网上找不到任何东西。此外,此(或非常相似)代码用于在以前(非核心)版本的 ASP.NET 中工作。

Get*_*awn 5

您需要在提取中设置凭据选项,这将执行以下操作:

Request 接口的凭据只读属性指示用户代理是否应该在跨域请求的情况下发送来自其他域的 cookie。这类似于 XHR 的 withCredentials 标志,但具有三个可用值(而不是两个)

  • omit: 永远不要发送cookies。
  • same-origin:如果 URL 与调用脚本来自同一来源,则发送用户凭据(cookies、基本 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));
Run Code Online (Sandbox Code Playgroud)