简体   繁体   中英

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

[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...

Meanwhile, using the jquery api, everything seems to work fine:

$.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.

You need to set the credentials option in the fetch, this does the following:

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. This is similar to XHR's withCredentials flag, but with three available values (instead of two)

  • omit : Never send cookies.
  • same-origin : Send user credentials (cookies, basic http auth, etc..) if the URL is on the same origin as the calling script. This is the default value.
  • include : Always send user credentials (cookies, basic http auth, etc..), even for cross-origin calls.

Source

Your fetch would now look like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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