Asp.Net Core 跨域处理_Ajax 跨域处理整理

一、Asp.Net Core 跨域处理_Ajax 跨域处理整理

Asp.Net Core中已经自带了跨域处理。

跨域处理,需要3步

1.配置跨域定义,在ConfigureServices中

public void ConfigureServices(IServiceCollection services)
{
    //定义配置跨域处理
    services.AddCors(options =>
    {
        //完全公开,不支持cookie传递
        options.AddPolicy("any", policy =>
        {
            policy.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
        });

        //指定域名公开,可以支持cookie
        options.AddPolicy("all", policy =>
        {
            policy.WithOrigins(
                "null", //file:///本地测试可以访问
                "http://localhost:8080",
                    "http://localhost:8081"
                )
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials();
        });
    });
}

2.开启跨域,在Configure中

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    //开启路由
    app.UseRouting();
    //开启 跨域处理,此代码必须放在 UseRouting() 和 UseEndpoints() 之间
    app.UseCors();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });

}

3.在控制器中,指定跨域公开

使用EnbleCore() 在控制器或者action 中指定

    [EnableCors("any")]
    [Route("[controller]/[action]/")]
    public class StuController : Controller
    {
    }

二、客户端完全公开

ajax请求都支持

        var url = 'http://localhost:52401/stu/getlist';
        $.get(url, {}, function (res) {
            console.info(res);
        });

三、客户端带cookie指定域名跨域

var url = 'http://localhost:52401/class/getcookie';
$.ajax({
    url: url,
    data: {},
    xhrFields: {
        withCredentials: true  //支持附带详细信息
    },
    crossDomain: true,//请求偏向外域
    success: function (res) {
        console.info(res);
    }
});

更多:

Ajax跨域请求附带Cookie/Ajax跨域请求附带身份凭证

Asp.Net WebApi 启用CORS跨域访问指定多个域名

Cors 跨域Access-Control-Allow-Origin

Ajax跨域请求中的Cookie问题(默认不带cookie等凭证)

原文地址:https://www.cnblogs.com/tianma3798/p/14254758.html