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

耗尽温柔 提交于 2020-01-04 03:58:09

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/50587560/js-fetch-api-not-working-with-asp-net-core-2-controllers-with-authorize-attribut

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!