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

I'm having the following code on the client side:fetch("musicindex", { headers: { &quo

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745661779a4638879.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信