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";
                    }
                }
            });
 

猜你喜欢

转载自blog.csdn.net/LanSeTianKong12/article/details/84308118