今天學習asp.net core webapi跨域(Cors)訪問

跨域的概念:

這裏說的跨域是指通過js在不同的域之間進行數據傳輸或通信,比如用ajax向一個不同的域請求數據,或者通過js獲取頁面中不同域的框架中(iframe)的數據。只要協議、域名、端口有任何一個不同,都被當作是不同的域。
默認瀏覽器是不支持直接跨域訪問的。但是由於種種原因我們又不得不進行跨域訪問,比如當前後端分離的方式開發程序是跨域是不可避免的。
而解決跨域的方式也比較簡單:
1、通過jsonp跨域
2、通過修改document.domain來跨子域

3、添加對服務端進行改造使其支持跨域。

接下來說說怎麼實現asp.net core webapi的跨域(Cors)訪問。

首先你得有個webapi的項目,並添加Microsoft.AspNetCore.Cors的包,然後在Startup中的ConfigureServices下配置新增如下代碼:



1             #region 跨域
2             var urls = Configuration["AppConfig:Cores"].Split(',');
3             services.AddCors(options =>
4             options.AddPolicy("AllowSameDomain",
5         builder => builder.WithOrigins(urls).AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials())
6             );
7             #endregion
複製代碼
1             #region 跨域
2             var urls = Configuration["AppConfig:Cores"].Split(',');
3             services.AddCors(options =>
4             options.AddPolicy("AllowSameDomain",
5         builder => builder.WithOrigins(urls).AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials())
6             );
7             #endregion
複製代碼

這樣asp.net core webapi就支持了跨域且支持cookie在跨域訪問時發送到服務端(不要問我爲什麼,仔細看看跨域所添加的頭就明白了)。

配置完跨域還需要寫明哪些控制器或方法可以跨域,之前看某大神的帖子說須在Startup的Configure中配置如下代碼:

 1 app.UseCors("AllowSameDomain");

複製代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Elisoft.PMForWechat.Web.App_Helper.Auth;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace Elisoft.PMForWechat.Web.App_Helper
{
    //啓用跨域
    [EnableCors("AllowSameDomain")]
    public class BaseController : Controller
    {
        public AuthManager _authManager { get { return new AuthManager(HttpContext); } }
    }
}
複製代碼

然後每個控制器集成上面定義的基礎控制器。

這樣整個asp.net core webapi之跨域(Cors)訪問 就配置完了。

最後貼一下在jquery的訪問代碼:

複製代碼
 1  $.ajax({
 2                 type: 'post',
 3                 url: interfac_url_content.Account_Login,
 4                 data: JSON.stringify(json),
 5                 contentType: 'application/json',
 6                 beforeSend: function () {
 7                     Loading("請稍等,數據提交中... ...");
 8                 },
 9 //必須有這項的配置,不然cookie無法發送至服務端
10       xhrFields: {
11               withCredentials: true
12             },
13                 success: function (json) {
14                     $.unblockUI();
15                     if (handleajaxresult(json)) {
16                         data=json.data;
17                         setCookie("Account",data.Account);
18                         window.location.href = "index.html#/pages/staff/index.html";
19                     }
20                 }
21             });

1             #region 跨域
2             var urls = Configuration["AppConfig:Cores"].Split(',');
3             services.AddCors(options =>
4             options.AddPolicy("AllowSameDomain",
5         builder => builder.WithOrigins(urls).AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials())
6             );
7             #endregion
複製代碼
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章