最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - JS Fetch API not working with ASP.NET Core 2 Controllers with Authorize attribute - Stack Overflow

matteradmin8PV0评论

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.

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.

Share Improve this question edited May 30, 2018 at 6:35 Dimitar Dimitrov asked May 29, 2018 at 15:03 Dimitar DimitrovDimitar Dimitrov 15.2k9 gold badges53 silver badges81 bronze badges 3
  • 1 have you tried adding the credentials: 'include' option? developer.mozilla/en-US/docs/Web/API/Request/credentials – Get Off My Lawn Commented May 29, 2018 at 15:05
  • @GetOffMyLawn dude, you rock, I didn't even know about this - it worked. Can you write it as an answer? – Dimitar Dimitrov Commented May 29, 2018 at 15:08
  • @RoryMcCrossan I don't have $.ajaxSetup() call anywhere, I presume the defaults are set so that it works. – Dimitar Dimitrov Commented May 29, 2018 at 15:12
Add a ment  | 

1 Answer 1

Reset to default 5

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));
Post a comment

comment list (0)

  1. No comments so far