JS Fetch API无法使用具有Authorize属性的ASP.NET Core 2控制器

问题描述 投票:3回答:1

我在客户端有以下代码:

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版本。

javascript c# jquery asp.net-core asp.net-core-2.0
1个回答
4
投票

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

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

  • omit:永远不要发送cookies。
  • same-origin:如果URL与调用脚本位于同一源,则发送用户凭据(cookie,基本http身份验证等)。这是默认值。
  • include:即使是跨域调用,也始终发送用户凭据(cookie,基本http身份验证等)。

Source

你的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));
© www.soinside.com 2019 - 2024. All rights reserved.