Skip to content

Commit

Permalink
feat(src/knifehub.web): add: Serilog.AspNetCore
Browse files Browse the repository at this point in the history
  • Loading branch information
yiyungent committed Dec 28, 2023
1 parent d5abaa8 commit 2332f93
Show file tree
Hide file tree
Showing 2 changed files with 138 additions and 107 deletions.
1 change: 1 addition & 0 deletions src/KnifeHub.Web/KnifeHub.Web.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.14.0" />
<PackageReference Include="Sentry.AspNetCore" Version="3.26.2" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
</ItemGroup>

Expand Down
244 changes: 137 additions & 107 deletions src/KnifeHub.Web/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Serilog;

namespace KnifeHub.Web
{
Expand All @@ -26,140 +27,169 @@ public class Program

public static void Main(string[] args)
{
for (var i = 0; i < args.Length; i++)
// https://github.com/serilog/serilog-aspnetcore
// https://github.com/serilog/serilog/wiki/Getting-Started
// Serilog.AspNetCore 已依赖 Serilog.Sinks.Console , Serilog.Sinks.File
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console()
.WriteTo.File($"logs/{nameof(KnifeHub)}.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();

try
{
System.Console.WriteLine($"args[{i}]: {args[i]}");
}
if (args.Contains("--no-console"))
{
System.Console.WriteLine("--no-console: hidden current console window");
// 获取控制台窗口句柄
var handle = GetConsoleWindow();
// 隐藏控制台窗口
ShowWindow(handle, SW_HIDE);
}
// 输出当前平台信息
Console.WriteLine($"CurrentPlatform: {Utils.OSUtil.PlatformInfo()}");
Log.Information("Starting web application");

var builder = WebApplication.CreateBuilder(args);
{
#region 启动参数
for (var i = 0; i < args.Length; i++)
{
System.Console.WriteLine($"args[{i}]: {args[i]}");
}
if (args.Contains("--no-console"))
{
System.Console.WriteLine("--no-console: hidden current console window");
// 获取控制台窗口句柄
var handle = GetConsoleWindow();
// 隐藏控制台窗口
ShowWindow(handle, SW_HIDE);
}
// 输出当前平台信息
Console.WriteLine($"CurrentPlatform: {Utils.OSUtil.PlatformInfo()}");
#endregion

// 配置注入
ConfigOptions configOptions = builder.Configuration.GetSection(ConfigOptions.Config).Get<ConfigOptions>();
builder.Services.Configure<ConfigOptions>(builder.Configuration.GetSection(ConfigOptions.Config));
var builder = WebApplication.CreateBuilder(args);

builder.WebHost.UseSentry(o =>
{
o.Dsn = "https://ed1fa11da1bb47188350fbcfcb6af159@o4504597240741888.ingest.sentry.io/4504597253980160";
// When configuring for the first time, to see what the SDK is doing:
//o.Debug = true;
// Set TracesSampleRate to 1.0 to capture 100% of transactions for performance monitoring.
// We recommend adjusting this value in production.
o.TracesSampleRate = 1.0;
});
// 配置注入
ConfigOptions configOptions = builder.Configuration.GetSection(ConfigOptions.Config).Get<ConfigOptions>();
builder.Services.Configure<ConfigOptions>(builder.Configuration.GetSection(ConfigOptions.Config));

//Sentry.SentrySdk.CaptureMessage("Hello Sentry");
#region Sentry
builder.WebHost.UseSentry(o =>
{
o.Dsn = "https://ed1fa11da1bb47188350fbcfcb6af159@o4504597240741888.ingest.sentry.io/4504597253980160";
// When configuring for the first time, to see what the SDK is doing:
//o.Debug = true;
// Set TracesSampleRate to 1.0 to capture 100% of transactions for performance monitoring.
// We recommend adjusting this value in production.
o.TracesSampleRate = 1.0;
});

// Add services to the container.
//Sentry.SentrySdk.CaptureMessage("Hello Sentry");
#endregion

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
// Add services to the container.

builder.Services.AddSwaggerGen(options =>
{
// 防止相同的 SchemaId 冲突
// https://stackoverflow.com/questions/61881770/invalidoperationexception-cant-use-schemaid-the-same-schemaid-is-already-us
options.CustomSchemaIds(type => type.ToString());
});
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();

#region 跨域配置
if (configOptions.AllowAllCors)
{
Console.WriteLine("跨域: AllowAllCors");
builder.Services.AddCors(m => m.AddPolicy("AllowAllCors", a => a.AllowAnyOrigin().AllowAnyHeader()));
}
else
{
Console.WriteLine("跨域: AllowedCorsOrigins");
#region CorsWhiteList
var corsWhiteList = configOptions.CorsWhiteList;
// 所有允许跨域的 Origin
List<string> allAllowedCorsOrigins = new List<string>();
if (corsWhiteList != null && corsWhiteList.Count > 0)
{
foreach (var item in corsWhiteList)
builder.Services.AddSwaggerGen(options =>
{
allAllowedCorsOrigins.Add(item);
}
// 防止相同的 SchemaId 冲突
// https://stackoverflow.com/questions/61881770/invalidoperationexception-cant-use-schemaid-the-same-schemaid-is-already-us
options.CustomSchemaIds(type => type.ToString());
});

// 允许 AspNetCoreClient 跨域请求
builder.Services.AddCors(options =>
#region 跨域配置
if (configOptions.AllowAllCors)
{
Console.WriteLine("跨域: AllowAllCors");
builder.Services.AddCors(m => m.AddPolicy("AllowAllCors", a => a.AllowAnyOrigin().AllowAnyHeader()));
}
else
{
options.AddPolicy(name: "AllowedCorsOrigins",
builder =>
Console.WriteLine("跨域: AllowedCorsOrigins");
#region CorsWhiteList
var corsWhiteList = configOptions.CorsWhiteList;
// 所有允许跨域的 Origin
List<string> allAllowedCorsOrigins = new List<string>();
if (corsWhiteList != null && corsWhiteList.Count > 0)
{
foreach (var item in corsWhiteList)
{
// ConfigOptions 里配置的白名单都允许
builder.WithOrigins(allAllowedCorsOrigins.ToArray())
allAllowedCorsOrigins.Add(item);
}

// 解决发送json,复杂请求问题: https://blog.csdn.net/yangyiboshigou/article/details/78738228
// 解决方法: Access-Control-Allow-Headers: Content-Type
// 参考: https://www.cnblogs.com/jpfss/p/10102132.html
.WithHeaders("Content-Type");
// 允许 AspNetCoreClient 跨域请求
builder.Services.AddCors(options =>
{
options.AddPolicy(name: "AllowedCorsOrigins",
builder =>
{
// ConfigOptions 里配置的白名单都允许
builder.WithOrigins(allAllowedCorsOrigins.ToArray())

// 解决发送json,复杂请求问题: https://blog.csdn.net/yangyiboshigou/article/details/78738228
// 解决方法: Access-Control-Allow-Headers: Content-Type
// 参考: https://www.cnblogs.com/jpfss/p/10102132.html
.WithHeaders("Content-Type");
});
});
});
}
#endregion
}
#endregion
}
#endregion
}
#endregion

builder.Services.AddPluginCore();
builder.Services.AddPluginCore();

var app = builder.Build();
var app = builder.Build();

// Performance monitoring
// Enable automatic tracing integration.
// If running with .NET 5 or below, make sure to put this middleware
// right after `UseRouting()`.
app.UseSentryTracing();
// Performance monitoring
// Enable automatic tracing integration.
// If running with .NET 5 or below, make sure to put this middleware
// right after `UseRouting()`.
app.UseSentryTracing();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

#region 跨域配置
if (configOptions.AllowAllCors)
{
app.UseCors("AllowAllCors");
Console.WriteLine("AllowAllCors");
}
else
{
app.UseCors("AllowedCorsOrigins");
Console.WriteLine("AllowedCorsOrigins");
}
#endregion
#region 跨域配置
if (configOptions.AllowAllCors)
{
app.UseCors("AllowAllCors");
Console.WriteLine("AllowAllCors");
}
else
{
app.UseCors("AllowedCorsOrigins");
Console.WriteLine("AllowedCorsOrigins");
}
#endregion

app.UsePluginCore();
app.UsePluginCore();

app.UseAuthorization();
app.UseAuthorization();

// wwwroot
app.UseStaticFiles(new StaticFileOptions()
{
// wwwroot
app.UseStaticFiles(new StaticFileOptions()
{

});
});

app.UseDefaultFiles(new DefaultFilesOptions()
{
DefaultFileNames = new[] { "index.html" }
});
app.UseDefaultFiles(new DefaultFilesOptions()
{
DefaultFileNames = new[] { "index.html" }
});

app.MapControllers();

app.MapControllers();
app.Run();
}
}
catch (Exception ex)
{
Log.Fatal(ex, "Application terminated unexpectedly");
}
finally
{
Log.CloseAndFlush();
}

app.Run();
}
}
}

0 comments on commit 2332f93

Please sign in to comment.