【问题标题】:JS Fetch API not working with ASP.NET Core 2 Controllers with Authorize attributeJS Fetch API 不适用于具有 Authorize 属性的 ASP.NET Core 2 控制器
【发布时间】:2018-11-08 07:09:24
【问题描述】:

我在客户端有以下代码:

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。

【问题讨论】:

  • 您是否尝试过添加credentials: 'include' 选项? developer.mozilla.org/en-US/docs/Web/API/Request/credentials
  • @GetOffMyLawn 伙计,你太棒了,我什至不知道这件事 - 它奏效了。你能把它写成答案吗?
  • @RoryMcCrossan 我在任何地方都没有$.ajaxSetup() 电话,我认为默认设置是为了让它工作。

标签: javascript c# jquery asp.net-core asp.net-core-2.0


【解决方案1】:

您需要在 fetch 中设置凭据选项,它执行以下操作:

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

  • omit:永远不要发送 cookie。
  • 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));

【讨论】:

  • 谢谢,我不知道我是如何在API 文档中错过的(我觉得有点愚蠢)。非常感谢。
  • 没问题。奇怪的是same-origin 是默认值,但它似乎从来没有工作过。
猜你喜欢
  • 2017-03-31
  • 2014-03-21
  • 1970-01-01
  • 2022-01-20
  • 2023-03-15
  • 1970-01-01
  • 2021-11-24
  • 1970-01-01
  • 2020-07-14
相关资源
最近更新 更多