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

这样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             });

 

参考文章:http://www.cnblogs.com/xishuai/p/aspnet-core-cors.html

 

 
posted @ 2016-11-23 13:38  xingbo  阅读(21164)  评论(3编辑  收藏  举报