網站首頁 編程語言 正文
一、后臺API接口
用.net core創建一個Web API項目負責給前端界面提供數據。
二、前端界面
建立兩個MVC項目,模擬不同的ip,在view里面添加按鈕調用WEB API提供的接口進行測試跨域。view視圖頁代碼如下:
@{ Layout = null; }跨域測試1
三、測試
1、不設置允許跨域
首先,先不設置.net core允許跨域,查看調用效果:
點擊測試跨域1按鈕:
F12進入Debug模式查看失敗原因:
從這里可以看出來是因為產生了跨域問題,所以會失敗。
點擊測試跨域2的效果和此效果一致。
2、設置允許所有來源跨域
2.1、在StartUp類的ConfigureServices方法中添加如下代碼:
// 配置跨域處理,允許所有來源 services.AddCors(options => options.AddPolicy("cors", p => p.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials()));
2.2、修改Configure方法
// 允許所有跨域,cors是在ConfigureServices方法中配置的跨域策略名稱 app.UseCors("cors");
2.3、測試
從截圖中可以看出,這次調用成功了。
3、設置特定來源可以跨域
3.1、修改ConfigureServices方法代碼如下:
//允許一個或多個來源可以跨域 services.AddCors(options => { options.AddPolicy("CustomCorsPolicy", policy => { // 設定允許跨域的來源,有多個可以用','隔開 policy.WithOrigins("http://localhost:21632") .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); });
這里設置只允許ip為http://localhost:21632的來源允許跨域。
3.2、修改Configure代碼如下:
// 設定特定ip允許跨域 CustomCorsPolicy是在ConfigureServices方法中配置的跨域策略名稱 app.UseCors("CustomCorsPolicy");
3.3測試
點擊跨域測試1按鈕,結果如下:
可以看到訪問成功了,然后在點擊跨域測試2按鈕,結果如下:
發現這次訪問失敗了,F12進入Debug模式,查看失敗原因:
從截圖中可以看出是因為這里產生了跨域請求,但是沒有允許跨域測試2所在的ip跨域。那么如果也想讓跨域測試2可以調用成功該怎么辦呢?
光標定位到WithOrigins上面,然后F12查看定義:
從截圖中發現:WithOrigins的參數是一個params類型的字符串數組,如果要允許多個來源可以跨域,只要傳一個字符串數組就可以了,所以代碼修改如下:
//允許一個或多個來源可以跨域 services.AddCors(options => { options.AddPolicy("CustomCorsPolicy", policy => { // 設定允許跨域的來源,有多個可以用','隔開 policy.WithOrigins("http://localhost:21632", "http://localhost:24661") .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); });
這時跨域測試2也可以調用成功了
4、優化
在上面的例子中,需要分兩步進行設置才可以允許跨域,有沒有一種方法只需要設置一次就可以呢?在Configure方法中只設置一次即可,代碼如下:
// 設置允許所有來源跨域 app.UseCors(options => { options.AllowAnyHeader(); options.AllowAnyMethod(); options.AllowAnyOrigin(); options.AllowCredentials(); }); // 設置只允許特定來源可以跨域 app.UseCors(options => { options.WithOrigins("http://localhost:3000", "http://127.0.0.1"); // 允許特定ip跨域 options.AllowAnyHeader(); options.AllowAnyMethod(); options.AllowCredentials(); });
5、利用配置文件實現跨域
在上面的示例中,都是直接把ip寫在了程序里面,如果要增加或者修改允許跨域的ip就要修改代碼,這樣非常不方便,那么能不能利用配置文件實現呢?看下面的例子。
5.1、修改appsettings.json文件如下:
{ "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": { "url": "http://localhost:21632|http://localhost:24663" } }
AllowedHosts里面設置的是允許跨域的ip,多個ip直接用“|”進行拼接,也可以用其他符合進行拼接。
5.2、增加CorsOptions實體類
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CorsDomainDemo { public class CorsOptions { public string url { get; set; } } }
5.3、 新增OptionConfigure方法
private void OptionConfigure(IServiceCollection services) { services.Configure(Configuration.GetSection("AllowedHosts")); }
5.4、在ConfigureServices方法里面調用OptionConfigure方法
// 讀取配置文件內容 OptionConfigure(services);
5.5、修改Configure方法,增加IOptions類型的參數,最終代碼如下
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace CorsDomainDemo { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // 配置跨域處理,允許所有來源 //services.AddCors(options => //options.AddPolicy("cors", //p => p.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials())); //允許一個或多個來源可以跨域 //services.AddCors(options => //{ // options.AddPolicy("CustomCorsPolicy", policy => // { // // 設定允許跨域的來源,有多個可以用','隔開 // policy.WithOrigins("http://localhost:21632", "http://localhost:24661") // .AllowAnyHeader() // .AllowAnyMethod() // .AllowCredentials(); // }); //}); // 讀取配置文件內容 OptionConfigure(services); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IOptionscorsOptions) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } // 允許所有跨域,cors是在ConfigureServices方法中配置的跨域策略名稱 //app.UseCors("cors"); // 設定特定ip允許跨域 CustomCorsPolicy是在ConfigureServices方法中配置的跨域策略名稱 //app.UseCors("CustomCorsPolicy"); // 設置允許所有來源跨域 //app.UseCors(options => //{ // options.AllowAnyHeader(); // options.AllowAnyMethod(); // options.AllowAnyOrigin(); // options.AllowCredentials(); //}); // 設置只允許特定來源可以跨域 //app.UseCors(options => //{ // options.WithOrigins("http://localhost:3000", "http://127.0.0.1"); // 允許特定ip跨域 // options.AllowAnyHeader(); // options.AllowAnyMethod(); // options.AllowCredentials(); //}); // 利用配置文件實現 CorsOptions _corsOption = corsOptions.Value; // 分割成字符串數組 string[] hosts = _corsOption.url.Split('|'); // 設置跨域 app.UseCors(options => { options.WithOrigins(hosts); options.AllowAnyHeader(); options.AllowAnyMethod(); options.AllowCredentials(); }); app.UseHttpsRedirection(); app.UseMvc(); } private void OptionConfigure(IServiceCollection services) { services.Configure (Configuration.GetSection("AllowedHosts")); } } }
這樣就可以實現利用配置文件實現允許跨域了。
原文鏈接:https://www.cnblogs.com/dotnet261010/p/10177166.html
相關推薦
- 2022-05-08 C++中如何修改const變量你知道嗎_C 語言
- 2022-04-16 python基礎之定義類和對象詳解_python
- 2022-01-16 jQuery 核心函數css和平滑滾動頂部
- 2023-10-31 IP地址、網關、網絡/主機號、子網掩碼關系
- 2022-08-11 C++通過boost.date_time進行時間運算_C 語言
- 2022-08-21 Mac包管理器Homebrew的安裝方法_其它綜合
- 2022-08-30 ORACLE分區表轉換在線重定義DBMS_REDEFINITION_oracle
- 2022-04-09 給原生html中添加水印遮罩層
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支