.netCore跨域设置

一、设置允许所有来源跨域

在StartUp类的ConfigureServices方法中添加如下代码:

// 配置跨域处理,允许所有来源
services.AddCors(options =>
options.AddPolicy("cors",
p => p.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials()));

修改Configure方法:

// 允许所有跨域,cors是在ConfigureServices方法中配置的跨域策略名称
app.UseCors("cors");

二、设置特定来源可以跨域

修改ConfigureServices方法代码如下:

//允许一个或多个来源可以跨域
services.AddCors(options =>
{
      options.AddPolicy("CustomCorsPolicy", policy =>
      {
             // 设定允许跨域的来源,有多个可以用','隔开
             policy.WithOrigins("http://localhost:21632")
             .AllowAnyHeader()
             .AllowAnyMethod()
             .AllowCredentials();
      });
});

这里设置只允许ip为http://localhost:21632的来源允许跨域。

修改Configure代码如下:

// 设定特定ip允许跨域 CustomCorsPolicy是在ConfigureServices方法中配置的跨域策略名称
app.UseCors("CustomCorsPolicy");
//允许一个或多个来源可以跨域
services.AddCors(options =>
{
      options.AddPolicy("CustomCorsPolicy", policy =>
      {
            // 设定允许跨域的来源,有多个可以用','隔开
            policy.WithOrigins("http://localhost:21632", "http://localhost:24661")
            .AllowAnyHeader()
            .AllowAnyMethod()
            .AllowCredentials();
      });
});

三、优化代码,一步设置跨域

// 设置允许所有来源跨域
app.UseCors(options =>
{
       options.AllowAnyHeader();
       options.AllowAnyMethod();
       options.AllowAnyOrigin();
       options.AllowCredentials();
});

// 设置只允许特定来源可以跨域
app.UseCors(options =>
{
        options.WithOrigins("http://localhost:3000", "http://127.0.0.1"); // 允许特定ip跨域
        options.AllowAnyHeader();
        options.AllowAnyMethod();
        options.AllowCredentials();
});

四、通过配置文件动态配置跨域

修改appsettings.json文件如下:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": {
    "url": "http://localhost:21632|http://localhost:24663"
  }
}

AllowedHosts里面设置的是允许跨域的ip,多个ip直接用“|”进行拼接,也可以用其他符合进行拼接。

增加CorsOptions实体类:

 public class CorsOptions
    {
        public string url { get; set; }
    }

全部代码如下:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Cors.Infrastructure;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;

namespace test.Server
{
    public class CorsOptions
    {
        public string url { get; set; }
    }

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // 读取配置文件内容
            OptionConfigure(services);
            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env,IOptions<CorsOptions> corsOptions)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthorization();

            // 利用配置文件实现
            //https://www.luweidong.cn/details/146
            CorsOptions _corsOption = corsOptions.Value;
            // 分割成字符串数组
            string[] hosts = _corsOption.url.Split('|');
            app.UseCors(options =>
            {
                options.WithOrigins(hosts); // 允许特定ip跨域
                options.AllowAnyHeader();
                options.AllowAnyMethod();
                options.AllowCredentials();
            });

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
        //新增OptionConfigure方法用于读取配置文件
        private void OptionConfigure(IServiceCollection services)
        {
            services.Configure<CorsOptions>(Configuration.GetSection("AllowedHosts"));
        }
    }
}

原文:https://www.luweidong.cn/details/146

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值