繁体   English   中英

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

[英]JS Fetch API not working with ASP.NET Core 2 Controllers with Authorize attribute

我在客户端有以下代码:

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

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

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

  • omit :永远不要发送cookie。
  • same-origin :如果URL与调用脚本位于同一原点,则发送用户凭据(cookie,基本http身份验证等)。 这是默认值。
  • include :始终发送用户凭据(cookie,基本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));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM