简体   繁体   English

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

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

I'm having the following code on the client side: 我在客户端有以下代码:

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));

Unfortunately this doesn't even reach the MusicController (server-side), which looks as follows (simplified to illustrate the point): 不幸的是,这甚至没有到达MusicController (服务器端),它看起来如下(简化以说明要点):

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

From what I see in the developer console I'm being redirected to /Account/Login?returnUrl... 从我在开发者控制台中看到的,我被重定向到/Account/Login?returnUrl...

Meanwhile, using the jquery api, everything seems to work fine: 同时,使用jquery api,一切似乎都运行正常:

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

I have a suspicion that I'm not setting my headers right? 我怀疑我没有设置我的标题吗? Not sure couldn't find anything on the net. 不确定在网上找不到任何东西。 Also this (or rather very similar) code used to work in previous (non-Core) versions of ASP.NET. 此代码(或非常类似的代码)也适用于以前的(非核心)ASP.NET版本。

You need to set the credentials option in the fetch, this does the following: 您需要在fetch中设置凭证选项,这将执行以下操作:

The credentials read-only property of the Request interface indicates whether the user agent should send cookies from the other domain in the case of cross-origin requests. Request接口的凭证只读属性指示用户代理是否应在跨源请求的情况下从其他域发送cookie。 This is similar to XHR's withCredentials flag, but with three available values (instead of two) 这类似于XHR的withCredentials标志,但有三个可用值(而不是两个)

  • omit : Never send cookies. omit :永远不要发送cookie。
  • same-origin : Send user credentials (cookies, basic http auth, etc..) if the URL is on the same origin as the calling script. same-origin :如果URL与调用脚本位于同一原点,则发送用户凭据(cookie,基本http身份验证等)。 This is the default value. 这是默认值。
  • include : Always send user credentials (cookies, basic http auth, etc..), even for cross-origin calls. include :始终发送用户凭据(cookie,基本http身份验证等),即使是跨域呼叫也是如此。

Source 资源

Your fetch would now look like this: 你的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