簡體   English   中英

JS Fetch API無法使用具有Authorize屬性的ASP.NET Core 2控制器

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

我在客戶端有以下代碼:

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版本。

您需要在fetch中設置憑證選項,這將執行以下操作:

Request接口的憑證只讀屬性指示用戶代理是否應在跨源請求的情況下從其他域發送cookie。 這類似於XHR的withCredentials標志,但有三個可用值(而不是兩個)

  • omit :永遠不要發送cookie。
  • same-origin :如果URL與調用腳本位於同一原點,則發送用戶憑據(cookie,基本http身份驗證等)。 這是默認值。
  • include :始終發送用戶憑據(cookie,基本http身份驗證等),即使是跨域呼叫也是如此。

資源

你的fetch現在看起來像這樣:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM