Reputation: 15158
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.
Upvotes: 3
Views: 4697
Reputation: 36341
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.
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));
Upvotes: 5