JS Fetch API无法与具有Authorize属性的ASP.NET Core 2控制器一起使用 [英] JS Fetch API not working with ASP.NET Core 2 Controllers with Authorize attribute

查看:80
本文介绍了JS Fetch API无法与具有Authorize属性的ASP.NET Core 2控制器一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在客户端有以下代码:

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

不幸的是,它甚至没有到达MusicController(服务器端),它看起来如下(简化说明了这一点):

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

根据我在开发人员控制台中看到的内容,我被重定向到/Account/Login?returnUrl...

From what I see in the developer console I'm being redirected to /Account/Login?returnUrl...

同时,使用jquery api,一切似乎都可以正常工作:

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

我怀疑我没有正确设置标题吗?不确定在网上找不到任何东西.同样,此(或非常相似的)代码也可以在以前的(非核心)ASP.NET版本中使用.

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:

请求"接口的凭据只读属性指示在进行跨域请求时,用户代理是否应从其他域发送cookie.这类似于XHR的withCredentials标志,但具有三个可用值(而不是两个)

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:从不发送cookie.
  • same-origin:如果URL与调用脚本的起源相同,则发送用户凭据(cookie,基本的HTTP auth等).这是默认值.
  • include:始终发送用户凭据(cookie,基本的http auth等),即使是跨域调用也是如此.
  • 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));

这篇关于JS Fetch API无法与具有Authorize属性的ASP.NET Core 2控制器一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆