flower-story/Server/Program.cs
2024-10-12 14:34:11 +08:00

120 lines
3.8 KiB
C#

using Blahblah.FlowerStory.Server.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace Blahblah.FlowerStory.Server;
/// <inheritdoc/>
public class Program
{
/// <inheritdoc/>
public const string ProjectName = "Flower Story";
/// <inheritdoc/>
public const string Version = "1.23.1226";
/// <inheritdoc/>
public static string DataPath =>
#if DEBUG
AppDomain.CurrentDomain.BaseDirectory;
#else
"/data";
#endif
/// <inheritdoc/>
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
options.OperationFilter<SwaggerHttpHeaderOperation>();
var scheme = new OpenApiSecurityScheme
{
Description = "授权头。 示例: \"RF4mfoUur0vHtWzHwD42ka0FhIfGaPnBxoQgrXOYEDg=\"",
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Authorization"
},
Scheme = "oauth2",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey
};
options.AddSecurityDefinition("Authorization", scheme);
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
[scheme] = Array.Empty<string>()
});
options.SwaggerDoc(Version, new OpenApiInfo
{
Title = ProjectName,
Version = Version,
Description = "<p>花事记录,贴心的帮您记录花园中的点点滴滴。</p><p><b>API 文档</b></p>"
});
options.IncludeXmlComments(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Server.xml"), true);
});
var dbPath = Path.Combine(DataPath, "flower.db");
builder.Services.AddDbContext<FlowerDatabase>(options => options.UseSqlite($"DataSource={dbPath};Cache=Shared"));
builder.Services.AddScoped<SwaggerGenerator>();
var app = builder.Build();
// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint($"/swagger/{Version}/swagger.json", ProjectName);
});
}
app.UseAuthorization();
app.UseStaticFiles();
app.MapControllers();
app.Run();
}
}
/// <inheritdoc/>
public class SwaggerHttpHeaderOperation : IOperationFilter
{
/// <inheritdoc/>
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
switch (context.ApiDescription.RelativePath)
{
case "api/user/auth":
operation.Parameters.Add(new OpenApiParameter
{
Name = "X-ClientAgent",
Description = "客户端代理",
In = ParameterLocation.Header,
Required = false,
Schema = new OpenApiSchema { Type = "string" }
});
operation.Parameters.Add(new OpenApiParameter
{
Name = "X-DeviceId",
Description = "设备 id",
In = ParameterLocation.Header,
Required = false,
Schema = new OpenApiSchema { Type = "string" }
});
break;
}
}
}