.Net中跨域问题

.Net中跨域问题

HTML页面

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Cors</title>
</head>
<body>
<button onclick="handlerClick()">跨域请求</button>
<p id="response"></p>
</body>
<script>
    const response = document.getElementById("response")
    const handlerClick = async () => {
        const responseText = (await fetch("http://localhost:5050/WeatherForecast")).json()
        responseText.then(data => {
            response.innerHTML = JSON.stringify(data)
        })
    }
</script>
</html>

跨域设置

全局配置跨域

csharp 复制代码
namespace Bunny.Cors.Net;

public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);
        // TODO 先处理跨域之后再访问控制器
        var serviceCollection = builder.Services;
        serviceCollection.AddCors(options =>
        {
            options.AddPolicy("BunnyApiCors", policyBuilder =>
            {
                policyBuilder.WithOrigins("*")
                    .WithHeaders("*")
                    .WithMethods("*");
            });
        });
        serviceCollection.AddControllers();
        serviceCollection.AddEndpointsApiExplorer();
        serviceCollection.AddSwaggerGen();

        var app = builder.Build();

        if (app.Environment.IsDevelopment())
        {
            app.UseSwagger();
            app.UseSwaggerUI();
        }

        app.UseHttpsRedirection();
        // TODO 使用跨域中间件
        app.UseCors("BunnyApiCors");
        app.UseAuthorization();
        app.MapControllers();
        app.Run();
    }
}

需要设置跨域

csharp 复制代码
var serviceCollection = builder.Services;
serviceCollection.AddCors(options =>
{
    options.AddPolicy("BunnyApiCors", policyBuilder =>
    {
        policyBuilder.WithOrigins("*")
            .WithHeaders("*")
            .WithMethods("*");
    });
});

使用跨域中间件

csharp 复制代码
// TODO 使用跨域中间件
app.UseCors("BunnyApiCors");

属性跨域

配置跨域
csharp 复制代码
namespace Bunny.DestinationNode.Net;

public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);
        // TODO 先处理跨域之后再访问控制器
        var serviceCollection = builder.Services;
        serviceCollection.AddCors(options =>
        {
            options.AddPolicy("BunnyApiCors", policyBuilder =>
            {
                policyBuilder.WithOrigins("*")
                    .WithHeaders("*")
                    .WithMethods("*");
            });
        });


        serviceCollection.AddControllers();
        serviceCollection.AddEndpointsApiExplorer();
        serviceCollection.AddSwaggerGen();

        var app = builder.Build();

        if (app.Environment.IsDevelopment())
        {
            app.UseSwagger();
            app.UseSwaggerUI();
        }

        app.UseHttpsRedirection();

        // TODO 使用跨域中间件
        app.UseCors();

        app.UseAuthorization();
        app.MapControllers();
        app.Run();
    }
}
控制器上操作

[EnableCors("BunnyApiCors")]这个操作也可以在方法上使用。

csharp 复制代码
[ApiController]
[Route("[controller]/")]
[EnableCors("BunnyApiCors")]
public class BunnyController : ControllerBase
{
    [HttpGet("GetBunny")]
    public string GetBunny()
    {
        return "bunny111";
    }
}

在方法上使用

csharp 复制代码
[ApiController]
[Route("[controller]/")]
public class BunnyController : ControllerBase
{
    [HttpGet("GetBunny")]
    [EnableCors("BunnyApiCors")]
    public string GetBunny()
    {
        return "bunny111";
    }
}

如果在类上使用了[EnableCors("BunnyApiCors")],但是某些方法不希望跨域可以这样。

在方法上使用注解[DisableCors]

csharp 复制代码
[HttpGet("GetBunny/Disable")]
[DisableCors]
public string GetBunnyDisable()
{
    return "bunny111";
}

默认策略

csharp 复制代码
var builder = WebApplication.CreateBuilder(args);
var serviceCollection = builder.Services;


// TODO 先处理跨域之后再访问控制器
serviceCollection.AddCors(options =>
{
    options.AddDefaultPolicy(policyBuilder => policyBuilder.WithOrigins("*")
        .WithHeaders("*")
        .WithMethods("*"));
});


serviceCollection.AddControllers();
serviceCollection.AddEndpointsApiExplorer();
serviceCollection.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();


// TODO 使用跨域中间件
app.UseCors();


app.UseAuthorization();
app.MapControllers();
app.Run();

需要指定默认策略AddDefaultPolicy

csharp 复制代码
// TODO 先处理跨域之后再访问控制器
serviceCollection.AddCors(options =>
{
    options.AddDefaultPolicy(policyBuilder => policyBuilder.WithOrigins("*")
        .WithHeaders("*")
        .WithMethods("*"));
});
相关推荐
步、步、为营1 小时前
.NET 如何实现ChatGPT的Stream传输
chatgpt·.net
喵叔哟5 小时前
37.【.NET8 实战--孢子记账--从单体到微服务--转向微服务】--扩展功能--增加Github Action
微服务·github·.net
步、步、为营5 小时前
.NET8 正式发布, C#12 新变化
ui·c#·.net
伽蓝_游戏6 小时前
Unity UI的未来之路:从UGUI到UI Toolkit的架构演进与特性剖析(7)
游戏·ui·unity·架构·c#·游戏引擎·.net
追逐时光者15 小时前
一款基于 .NET + Vue 编写的仿钉钉的开源低代码工作流引擎,支持多种数据库,开箱即用!
后端·.net
CodeCraft Studio19 小时前
使用 Aspose.OCR 将图像文本转换为可编辑文本
java·人工智能·python·ocr·.net·aspose·ocr工具
Kookoos20 小时前
ABP VNext + Quartz.NET vs Hangfire:灵活调度与任务管理
c#·.net·hangfire·quartz.net·abp vnext
时光追逐者1 天前
C#/.NET/.NET Core优秀项目和框架2025年7月简报
c#·.net·.netcore
伽蓝_游戏2 天前
Unity UI的未来之路:从UGUI到UI Toolkit的架构演进与特性剖析(6)
游戏·ui·unity·架构·c#·游戏引擎·.net
FuckPatience2 天前
Winform 渐变色 调色板
.net