开发更新

master
bicijinlian 4 years ago
parent fafa5ae02a
commit 0d0916ae44

@ -47,10 +47,10 @@
<body> <body>
<div id="MenuLinks"> <div id="MenuLinks">
<ul> <ul>
<li method="GET" dataType="json" contentType="application/x-www-form-urlencoded" url="http://localhost:5000/api/Test/Ping">简单API</li> <li method="GET" dataType="json" contentType="application/x-www-form-urlencoded" url="http://localhost:7050/api/Test/Ping">简单API</li>
<li method="GET" dataType="json" contentType="application/x-www-form-urlencoded" url="http://localhost:5000/api/Cors/Ping">全局跨域策略</li> <li method="GET" dataType="json" contentType="application/x-www-form-urlencoded" url="http://localhost:7050/api/Cors/Ping">全局跨域策略</li>
<li method="GET" dataType="json" contentType="application/x-www-form-urlencoded" url="http://localhost:5000/api/Cors/NoCors">不允许跨域</li> <li method="GET" dataType="json" contentType="application/x-www-form-urlencoded" url="http://localhost:7050/api/Cors/NoCors">不允许跨域</li>
<li method="PUT" dataType="json" contentType="application/x-www-form-urlencoded" url="http://localhost:5000/api/Cors/HasCors">单独明确可以跨域</li> <li method="PUT" dataType="json" contentType="application/x-www-form-urlencoded" url="http://localhost:7050/api/Cors/HasCors">单独明确可以跨域</li>
</ul> </ul>
</div> </div>
<pre id="ContentBox"> <pre id="ContentBox">

@ -5,12 +5,10 @@ using System.Threading.Tasks;
namespace CorsServer.WebApi31 namespace CorsServer.WebApi31
{ {
public class ApiConst
{
}
public class CorsPolicyNameConst public class ApplicationConst
{ {
public const string DefaultPolicyName = "AllowAll"; public const string DefaultPolicyName = "AllowAll";
public const string CorsConfigOptionName = "CorsOption";
} }
} }

@ -38,7 +38,7 @@ namespace CorsServer.WebApi31.Controllers
[HttpDelete] [HttpDelete]
[HttpPatch] [HttpPatch]
[HttpOptions] [HttpOptions]
[EnableCors(CorsPolicyNameConst.DefaultPolicyName)] [EnableCors(ApplicationConst.DefaultPolicyName)]
public IActionResult HasCors() public IActionResult HasCors()
{ {
var data = new { Code = 0, Messge = "单独明确可以跨域" }; var data = new { Code = 0, Messge = "单独明确可以跨域" };

@ -4,7 +4,7 @@
"windowsAuthentication": false, "windowsAuthentication": false,
"anonymousAuthentication": true, "anonymousAuthentication": true,
"iisExpress": { "iisExpress": {
"applicationUrl": "http://localhost:40118", "applicationUrl": "http://localhost:7050",
"sslPort": 0 "sslPort": 0
} }
}, },
@ -21,7 +21,7 @@
"commandName": "Project", "commandName": "Project",
"launchBrowser": true, "launchBrowser": true,
"launchUrl": "api/Test/Ping", "launchUrl": "api/Test/Ping",
"applicationUrl": "http://localhost:5000", "applicationUrl": "http://localhost:7050",
"environmentVariables": { "environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development" "ASPNETCORE_ENVIRONMENT": "Development"
} }

@ -26,10 +26,11 @@ namespace CorsServer.WebApi31
public void ConfigureServices(IServiceCollection services) public void ConfigureServices(IServiceCollection services)
{ {
//Config //Config
services.Configure<CorsOption>(Configuration.GetSection("CORS")); services.Configure<CorsOption>(Configuration.GetSection(ApplicationConst.CorsConfigOptionName));
#region CORS #region CORS
AddCors_Test(services); AddCors_Config(services);
//AddCors_Test(services);
//AddCors_2(services); //AddCors_2(services);
//AddCors_3(services); //AddCors_3(services);
//AddCors_4(services); //AddCors_4(services);
@ -43,17 +44,49 @@ namespace CorsServer.WebApi31
if (env.IsDevelopment()) if (env.IsDevelopment())
{ {
app.UseDeveloperExceptionPage(); app.UseDeveloperExceptionPage();
//app.UseDatabaseErrorPage();
} }
else
{
//app.UseExceptionHandler("/Error");
//app.UseHsts();
}
// app.UseHttpsRedirection();
#region 压缩和绑在静态文件
// app.UseResponseCompression();
// app.UseResponseCaching();
#endregion
// app.UseStaticFiles();
// app.UseCookiePolicy();
// ¸ù·¾¶£ºÈ«¾Ö·ÃÎÊÇ°ê¡ http://www.custom.com/PathBase/ // ¸ù·¾¶£ºÈ«¾Ö·ÃÎÊÇ°ê¡ http://www.custom.com/PathBase/
// app.UsePathBase("/api/"); // app.UsePathBase("/api/");
app.UseRouting(); app.UseRouting();
app.UseCors(CorsPolicyNameConst.DefaultPolicyName); // app.UseRequestLocalization();
// UseRouting() 和 UseAuthentication()之间
// 中间件顺序 https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/?view=aspnetcore-6.0#middleware-order
app.UseCors(ApplicationConst.DefaultPolicyName);
//app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();
//请在 Cookie策略中间件之后和 MVC中间件之前调用会话中间件。
// app.UseSession();
// app.UseResponseCompression();
// app.UseResponseCaching();
//自定义中间件
app.UseEndpoints(endpoints => app.UseEndpoints(endpoints =>
{ {
endpoints.MapControllers(); endpoints.MapControllers();
@ -68,7 +101,7 @@ namespace CorsServer.WebApi31
services.AddCors(setup => services.AddCors(setup =>
{ {
var corsOption = services.BuildServiceProvider().GetRequiredService<IOptionsSnapshot<CorsOption>>().Value; var corsOption = services.BuildServiceProvider().GetRequiredService<IOptionsSnapshot<CorsOption>>().Value;
setup.AddPolicy(CorsPolicyNameConst.DefaultPolicyName, build => setup.AddPolicy(ApplicationConst.DefaultPolicyName, build =>
{ {
build build
@ -120,7 +153,7 @@ namespace CorsServer.WebApi31
{ {
services.AddCors(setup => services.AddCors(setup =>
{ {
setup.AddPolicy(CorsPolicyNameConst.DefaultPolicyName, build => setup.AddPolicy(ApplicationConst.DefaultPolicyName, build =>
{ {
build build
@ -171,7 +204,7 @@ namespace CorsServer.WebApi31
{ {
services.AddCors(setup => services.AddCors(setup =>
{ {
setup.AddPolicy(CorsPolicyNameConst.DefaultPolicyName, build => setup.AddPolicy(ApplicationConst.DefaultPolicyName, build =>
{ {
build build
@ -209,7 +242,7 @@ namespace CorsServer.WebApi31
{ {
services.AddCors(setup => services.AddCors(setup =>
{ {
setup.AddPolicy(CorsPolicyNameConst.DefaultPolicyName, build => setup.AddPolicy(ApplicationConst.DefaultPolicyName, build =>
{ {
build build
@ -243,7 +276,7 @@ namespace CorsServer.WebApi31
{ {
services.AddCors(setup => services.AddCors(setup =>
{ {
setup.AddPolicy(CorsPolicyNameConst.DefaultPolicyName, build => setup.AddPolicy(ApplicationConst.DefaultPolicyName, build =>
{ {
build build
.AllowAnyOrigin() .AllowAnyOrigin()
@ -261,7 +294,7 @@ namespace CorsServer.WebApi31
services.AddCors(setup => services.AddCors(setup =>
{ {
var corsOption = services.BuildServiceProvider().GetRequiredService<IOptionsSnapshot<CorsOption>>().Value; var corsOption = services.BuildServiceProvider().GetRequiredService<IOptionsSnapshot<CorsOption>>().Value;
setup.AddPolicy(CorsPolicyNameConst.DefaultPolicyName, build => setup.AddPolicy(ApplicationConst.DefaultPolicyName, build =>
{ {
build build
.WithOrigins(corsOption.Origins.ToArray()) .WithOrigins(corsOption.Origins.ToArray())
@ -278,7 +311,7 @@ namespace CorsServer.WebApi31
{ {
services.AddCors(setup => services.AddCors(setup =>
{ {
setup.AddPolicy(CorsPolicyNameConst.DefaultPolicyName, build => setup.AddPolicy(ApplicationConst.DefaultPolicyName, build =>
{ {
build.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().WithExposedHeaders("x-custom-error"); build.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().WithExposedHeaders("x-custom-error");
}); });
@ -291,7 +324,7 @@ namespace CorsServer.WebApi31
services.AddCors(setup => services.AddCors(setup =>
{ {
var corsOption = services.BuildServiceProvider().GetRequiredService<IOptionsSnapshot<CorsOption>>().Value; var corsOption = services.BuildServiceProvider().GetRequiredService<IOptionsSnapshot<CorsOption>>().Value;
setup.AddPolicy(CorsPolicyNameConst.DefaultPolicyName, builder => setup.AddPolicy(ApplicationConst.DefaultPolicyName, builder =>
{ {
builder builder
////.SetIsOriginAllowedToAllowWildcardSubdomains() ////.SetIsOriginAllowedToAllowWildcardSubdomains()
@ -313,7 +346,7 @@ namespace CorsServer.WebApi31
services.AddCors(setup => services.AddCors(setup =>
{ {
var corsOption = services.BuildServiceProvider().GetRequiredService<IOptionsSnapshot<CorsOption>>().Value; var corsOption = services.BuildServiceProvider().GetRequiredService<IOptionsSnapshot<CorsOption>>().Value;
setup.AddPolicy(CorsPolicyNameConst.DefaultPolicyName, builder => setup.AddPolicy(ApplicationConst.DefaultPolicyName, builder =>
{ {
if (corsOption.Origins == null) if (corsOption.Origins == null)
{ {
@ -337,6 +370,10 @@ namespace CorsServer.WebApi31
{ {
builder.AllowAnyMethod(); builder.AllowAnyMethod();
} }
else if (corsOption.Methods.Contains("*"))
{
builder.AllowAnyMethod();
}
else else
{ {
builder.WithMethods(corsOption.Methods.ToArray()); builder.WithMethods(corsOption.Methods.ToArray());
@ -346,6 +383,11 @@ namespace CorsServer.WebApi31
{ {
builder.AllowAnyHeader(); builder.AllowAnyHeader();
} }
else if (corsOption.Headers.Contains("*"))
{
builder.AllowAnyHeader();
}
else else
{ {
builder.WithMethods(corsOption.Headers.ToArray()); builder.WithMethods(corsOption.Headers.ToArray());

@ -26,7 +26,7 @@ namespace CorsServer.WebApi31
public void ConfigureServices(IServiceCollection services) public void ConfigureServices(IServiceCollection services)
{ {
//Config //Config
services.Configure<CorsOption>(Configuration.GetSection("CORS")); services.Configure<CorsOption>(Configuration.GetSection(ApplicationConst.CorsConfigOptionName));
//CorsÅäÖÃÎļþÑ¡Ïî //CorsÅäÖÃÎļþÑ¡Ïî
AddCors_Config(services); AddCors_Config(services);
@ -43,7 +43,7 @@ namespace CorsServer.WebApi31
app.UseRouting(); app.UseRouting();
app.UseCors(CorsPolicyNameConst.DefaultPolicyName); app.UseCors(ApplicationConst.DefaultPolicyName);
app.UseAuthorization(); app.UseAuthorization();
@ -53,14 +53,12 @@ namespace CorsServer.WebApi31
}); });
} }
#region 注册不同的Cors策略
private IServiceCollection AddCors_Config(IServiceCollection services) private IServiceCollection AddCors_Config(IServiceCollection services)
{ {
services.AddCors(setup => services.AddCors(setup =>
{ {
var corsOption = services.BuildServiceProvider().GetRequiredService<IOptionsSnapshot<CorsOption>>().Value; var corsOption = services.BuildServiceProvider().GetRequiredService<IOptionsSnapshot<CorsOption>>().Value;
setup.AddPolicy(CorsPolicyNameConst.DefaultPolicyName, builder => setup.AddPolicy(ApplicationConst.DefaultPolicyName, builder =>
{ {
if (corsOption.Origins == null) if (corsOption.Origins == null)
{ {
@ -121,7 +119,5 @@ namespace CorsServer.WebApi31
return services; return services;
} }
#endregion
} }
} }

@ -25,11 +25,20 @@ namespace CorsServer.WebApi31
public void ConfigureServices(IServiceCollection services) public void ConfigureServices(IServiceCollection services)
{ {
//config //ÉèÖÃĬÈϲßÂÔCors
services.Configure<CorsOption>(Configuration.GetSection("CORS")); services.AddCors(setupCors =>
{
//Cors //ĬÈϲßÂÔ
AddDefaultCors(services); setupCors.AddDefaultPolicy(build =>
{
build
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.SetPreflightMaxAge(TimeSpan.FromMinutes(10))
;
});
});
services.AddControllers(); services.AddControllers();
} }
@ -41,9 +50,6 @@ namespace CorsServer.WebApi31
app.UseDeveloperExceptionPage(); app.UseDeveloperExceptionPage();
} }
//根路径:全局访问前辍 http://www.custom.com/PathBase/
//app.UsePathBase("/api/");
app.UseRouting(); app.UseRouting();
app.UseCors(); app.UseCors();
@ -55,26 +61,5 @@ namespace CorsServer.WebApi31
endpoints.MapControllers(); endpoints.MapControllers();
}); });
} }
/// <summary>
/// 设置默认策略Cors
/// </summary>
private IServiceCollection AddDefaultCors(IServiceCollection services)
{
services.AddCors(setupCors =>
{
setupCors.AddDefaultPolicy(build =>
{
build
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.SetPreflightMaxAge(TimeSpan.FromMinutes(10))
;
});
});
return services;
}
} }
} }

@ -1,6 +1,6 @@
{ {
"urls": "http://*:5000", "urls": "http://*:7050",
"CORS": { "CorsOption": {
"Origins": ["*"], "Origins": ["*"],
"Methods": [ "*" ], "Methods": [ "*" ],
"Headers": [ "*" ], "Headers": [ "*" ],

Loading…
Cancel
Save