.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("*"));
});
相关推荐
一丝晨光14 小时前
Java、PHP、ASP、JSP、Kotlin、.NET、Go
java·kotlin·go·php·.net·jsp·asp
yufei-coder15 小时前
C#基础语法
开发语言·c#·.net
Mudrock__16 小时前
前后端传输文件(图片)
vue·.net
时光追逐者2 天前
WaterCloud:一套基于.NET 8.0 + LayUI的快速开发框架,完全开源免费!
前端·microsoft·开源·c#·.net·layui·.netcore
friklogff2 天前
【C#生态园】打造现代化跨平台应用:深度解析.NET桌面应用工具
开发语言·c#·.net
@Unity打怪升级2 天前
【C#】CacheManager:高效的 .NET 缓存管理库
开发语言·后端·机器学习·缓存·c#·.net·.netcore
yufei-coder3 天前
.Net 9与AI开发
人工智能·.net
孟章豪3 天前
深入理解.NET中的委托与事件:实现灵活的事件驱动编程
.net
小彰5 天前
.Net 6.0 Windows平台如何判断当前电脑是否联网
windows·.net
小码编匠5 天前
.NET 中的表达式树(Expression Trees)
后端·c#·.net