编程语言
首页 > 编程语言> > javascript-JS Fetch API无法与具有Authorize属性的ASP.NET Core 2控制器一起使用

javascript-JS Fetch API无法与具有Authorize属性的ASP.NET Core 2控制器一起使用

作者:互联网

我在客户端有以下代码:

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(服务器端),它看起来如下所示(简化说明了这一点):

[Authorize]
public class MusicController : Controller {
    public async Task<IActionResult> Index() {        
        IEnumerable<Song> songs = await _songsRepository.GetAll();
        return Json(songs);
    }
}

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

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

$.get("/music/index")
    .done(json => console.log("Done! It's all good"))
    .fail(error => console.log(error));

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

解决方法:

您需要在提取中设置凭据选项,这将执行以下操作:

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

您的提取现在看起来像这样:

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

标签:asp-net-core,asp-net-core-2-0,javascript,c,jquery
来源: https://codeday.me/bug/20191025/1926347.html