1. 程式人生 > >asp.net core webapi之跨域(Cors)訪問

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下配置新增如下
程式碼:
#region 跨域
            var urls = Configuration["AppConfig:Cores"].Split(',');
            services.AddCors(options =>
            options.AddPolicy("AllowSameDomain",
        builder => builder.WithOrigins(urls).AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials())
            );
            #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的訪問程式碼:

$.ajax({
                type: 'post',
                url: interfac_url_content.Account_Login,
                data: JSON.stringify(json),
                contentType: 'application/json',
                beforeSend: function () {
                    Loading("請稍等,資料提交中... ...");
                },
//必須有這項的配置,不然cookie無法傳送至服務端
      xhrFields: {
              withCredentials: true
            },
                success: function (json) {
                    $.unblockUI();
                    if (handleajaxresult(json)) {
                        data=json.data;
                        setCookie("Account",data.Account);
                        window.location.href = "index.html#/pages/staff/index.html";
                    }
                }
            });