.NET 5.0 跨域请求配置

.NET 5.0 跨域请求配置

  • 允许任何IP地址和端口的请求
  • 允许指定IP地址和端口的请求(此为ABP的方法)

允许任何IP地址和端口的请求

首先startup的ConfigureServices中添加

			services.AddCors(
                options => options.AddPolicy(
                    "any",
                    builder => builder
                    .AllowAnyOrigin()
                )
            );

其次在Configure中添加

			app.UseRouting();
            app.UseAuthentication();
            app.UseAbpRequestLocalization();
            app.UseCors("any");

允许指定IP地址和端口的请求(此为ABP的方法)

首先startup的ConfigureServices中添加

		services.AddCors(
                options => options.AddPolicy(
                    _defaultCorsPolicyName,
                    builder => builder
                        .WithOrigins(
                            _appConfiguration["App:CorsOrigins"]
                                .Split(",", StringSplitOptions.RemoveEmptyEntries)
                                .Select(o => o.RemovePostFix("/"))
                                .ToArray()
                        )
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials()
                )
            );

其次在Configure中添加

			app.UseRouting();
            app.UseAuthentication();
            app.UseAbpRequestLocalization();

然后在appsettings.json中添加

 "App": {
    "ServerRootAddress": "XXXXXXXX",
    "ClientRootAddress": "XXXXXXXX",
    "CorsOrigins": "http://XXXX:XXX,http://XXXX:XXX"
  },

PS:
参数:_appConfiguration=>private readonly IConfigurationRoot _appConfiguration;
_defaultCorsPolicyName=> private const string _defaultCorsPolicyName = “localhost”;

你可能感兴趣的:(.NET,c#)