.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 小时前
winform迁移:从.net framework 到 .net9
.net·迁移·.net framework
TeamDev1 小时前
使用 Shadcn UI 构建 C# 桌面应用
前端·后端·.net
CodeCraft Studio1 小时前
CADSoftTools发布两款重要更新:CAD VCL Multiplatform 16.2 与 CAD .NET 16全新发布
.net·cad vcl·cad .net·cad文件格式解析·cad文件编辑·cad文件查看器
唐青枫4 小时前
C#.NET FluentSqlKata 全面解析:基于链式语法的动态 SQL 构建
c#·.net
用户2986985301420 小时前
Spire.Doc 实践指南:将Word 文档转换为 XML
后端·.net
忧郁的蛋~1 天前
.NET实现多任务异步与并行处理的详细步骤
后端·c#·asp.net·.net·.netcore
许泽宇的技术分享1 天前
Windows MCP.Net:解锁AI助手的Windows桌面自动化潜能
人工智能·windows·.net·mcp
搬砖的工人1 天前
记录WinFrom 使用 Autoupdater.NET.Official 进行软件升级更新
java·前端·.net
唐青枫1 天前
C#.NET SqlKata 使用详解:优雅构建动态 SQL 查询
c#·.net
追逐时光者2 天前
一个基于 .NET 开源、功能强大的分布式微服务开发框架
后端·.net