1. 程式人生 > >.net core實現跨域

.net core實現跨域

什麼是跨域在前面已經講解過了,這裡便不再講解,直接上程式碼。

一、後臺API介面

用.net core建立一個Web API專案負責給前端介面提供資料。

二、前端介面

建立兩個MVC專案,模擬不同的ip,在view裡面新增按鈕呼叫WEB API提供的介面進行測試跨域。view檢視頁程式碼如下:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>跨域測試1</title>
    <script src="
~/Scripts/jquery-1.10.2.js"></script> <script> function btnGet() { $.ajax({ url: 'https://localhost:44355/api/values', type: "Get", dataType: "json", success: function (data) { alert("成功
"); }, error: function (data) { alert("失敗"); } }); } </script> </head> <body> <div> <input type="button" id="btn" value="測試跨域" onclick="btnGet()" /> </div> </body> </html>

三、測試

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<CorsOptions>(Configuration.GetSection("AllowedHosts"));
}

 

5.4、在ConfigureServices方法裡面呼叫OptionConfigure方法

// 讀取配置檔案內容
OptionConfigure(services);

 

5.5、修改Configure方法,增加IOptions<CorsOptions>型別的引數,最終程式碼如下

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, IOptions<CorsOptions> corsOptions)
        {
            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<CorsOptions>(Configuration.GetSection("AllowedHosts"));
        }
    }
}

 

這樣就可以實現利用配置檔案實現允許跨域了。