關於.Net Core 前後端分離跨域請求時 ajax並發請求導致部分無法通過驗證解決辦法。
阿新 • • 發佈:2018-10-10
figure mvc control head configure onf light 請求 並發
項目中有這樣一個頁面。頁面加載的時候會同時並發6個ajax請求去後端請求下拉框。
這樣會導致每次都有1~2個“瀏覽器預請求”不通過。
瀏覽器為什麽會自動發送“預請求”?請看以面連接
https://blog.csdn.net/charleslei/article/details/51906635
那麽解決辦法無非就是盡量避免發送“預請求”。
後來經過反復測試發現“預請求”可以通過設置Access-Control-Max-Age來緩存。
在.Net Core 中我們可以通過如下代碼設置緩存:
public void ConfigureServices(IServiceCollection services) {//配置跨域訪問 var urls = Configuration.GetSection("AllowCors:AllowAllOrigin").Value.Split(‘,‘); services.AddCors(options => { options.AddPolicy("AllowAllOrigin", builder => { builder.WithOrigins(urls).AllowAnyMethod().AllowAnyHeader().AllowCredentials().SetPreflightMaxAge(TimeSpan.FromSeconds(1728000)); }); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }
使用
SetPreflightMaxAge方法設置即可。單位為秒
關於.Net Core 前後端分離跨域請求時 ajax並發請求導致部分無法通過驗證解決辦法。