.Net中跨域问题

.Net中跨域问题

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>

跨域设置

全局配置跨域

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

需要设置跨域

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

使用跨域中间件

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

属性跨域

配置跨域
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")]这个操作也可以在方法上使用。

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

在方法上使用

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

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

在方法上使用注解[DisableCors]

[HttpGet("GetBunny/Disable")]
[DisableCors]
public string GetBunnyDisable()
{
    return "bunny111";
}

默认策略

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

// TODO 先处理跨域之后再访问控制器
serviceCollection.AddCors(options =>
{
    options.AddDefaultPolicy(policyBuilder => policyBuilder.WithOrigins("*")
        .WithHeaders("*")
        .WithMethods("*"));
});
  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值