From 23de2ae7e23fce89b334ed73a9d83d8a45097d3b Mon Sep 17 00:00:00 2001 From: yubaolee Date: Fri, 12 Sep 2025 20:19:57 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9Bfix:=E4=BF=AE=E5=A4=8D=E6=AD=A3?= =?UTF-8?q?=E5=BC=8F=E7=8E=AF=E5=A2=83=E6=B2=A1=E6=9C=89=E5=85=B3=E9=97=AD?= =?UTF-8?q?SWAGGER?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .cursor/rules/openauth.mdc | 1 + Dockerfile | 5 + .../Controllers/SystemController.cs | 41 +++++ OpenAuth.WebApi/Startup.cs | 145 ++++++++++-------- 4 files changed, 124 insertions(+), 68 deletions(-) create mode 100644 OpenAuth.WebApi/Controllers/SystemController.cs diff --git a/.cursor/rules/openauth.mdc b/.cursor/rules/openauth.mdc index ec6d564e..fc54196d 100644 --- a/.cursor/rules/openauth.mdc +++ b/.cursor/rules/openauth.mdc @@ -38,6 +38,7 @@ OpenAuth.Net是一个基于.NET 9的企业级权限管理和快速开发框架 - 私有字段使用_camelCase,公共属性使用PascalCase - 常量使用UPPER_CASE - 异步方法必须添加Async后缀 +- 修改完代码后不需要编译 ### 命名规范 - **Controller**: 以Controller结尾,如`UsersController` diff --git a/Dockerfile b/Dockerfile index 31be1434..4978c32a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -28,6 +28,11 @@ RUN dotnet publish -c Release -o /app/publish/identity FROM base AS final WORKDIR /app + +# 设置 Production 环境变量 +ENV ASPNETCORE_ENVIRONMENT=Production +ENV DOTNET_ENVIRONMENT=Production + # 复制 WebApi 发布文件 COPY --from=build /app/publish/webapi ./webapi diff --git a/OpenAuth.WebApi/Controllers/SystemController.cs b/OpenAuth.WebApi/Controllers/SystemController.cs new file mode 100644 index 00000000..0ae5c512 --- /dev/null +++ b/OpenAuth.WebApi/Controllers/SystemController.cs @@ -0,0 +1,41 @@ +using System; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Hosting; + +namespace OpenAuth.WebApi.Controllers +{ + /// + /// 系统信息相关接口 + /// + [Route("api/[controller]/[action]")] + [ApiController] + public class SystemController : ControllerBase + { + private readonly IHostEnvironment _environment; + + public SystemController(IHostEnvironment environment) + { + _environment = environment; + } + + /// + /// 获取系统环境信息 + /// + /// + [HttpGet] + [AllowAnonymous] + public IActionResult GetEnvironmentInfo() + { + return Ok(new + { + EnvironmentName = _environment.EnvironmentName, + IsDevelopment = _environment.IsDevelopment(), + IsProduction = _environment.IsProduction(), + IsStaging = _environment.IsStaging(), + SwaggerEnabled = _environment.IsDevelopment(), // Swagger 只在开发环境启用 + Timestamp = DateTime.Now + }); + } + } +} \ No newline at end of file diff --git a/OpenAuth.WebApi/Startup.cs b/OpenAuth.WebApi/Startup.cs index c5d8e320..4df7b53b 100644 --- a/OpenAuth.WebApi/Startup.cs +++ b/OpenAuth.WebApi/Startup.cs @@ -61,67 +61,73 @@ namespace OpenAuth.WebApi }); } - // 添加MiniProfiler服务 - services.AddMiniProfiler(options => + // 只在开发环境中添加MiniProfiler服务 + if (Environment.IsDevelopment()) { - // 设定访问分析结果URL的路由基地址 - options.RouteBasePath = "/profiler"; + services.AddMiniProfiler(options => + { + // 设定访问分析结果URL的路由基地址 + options.RouteBasePath = "/profiler"; - options.ColorScheme = StackExchange.Profiling.ColorScheme.Auto; - options.PopupRenderPosition = StackExchange.Profiling.RenderPosition.BottomLeft; - options.PopupShowTimeWithChildren = true; - options.PopupShowTrivial = true; - options.SqlFormatter = new StackExchange.Profiling.SqlFormatters.InlineFormatter(); - // options.IgnoredPaths.Add("/swagger/"); - }).AddEntityFramework(); //显示SQL语句及耗时 + options.ColorScheme = StackExchange.Profiling.ColorScheme.Auto; + options.PopupRenderPosition = StackExchange.Profiling.RenderPosition.BottomLeft; + options.PopupShowTimeWithChildren = true; + options.PopupShowTrivial = true; + options.SqlFormatter = new StackExchange.Profiling.SqlFormatters.InlineFormatter(); + // options.IgnoredPaths.Add("/swagger/"); + }).AddEntityFramework(); //显示SQL语句及耗时 + } - //添加swagger - services.AddSwaggerGen(option => + // 只在开发环境中添加swagger + if (Environment.IsDevelopment()) { - foreach (var controller in GetControllers()) + services.AddSwaggerGen(option => { - var groupname = GetSwaggerGroupName(controller); - - option.SwaggerDoc(groupname, new OpenApiInfo + foreach (var controller in GetControllers()) { - Version = "v1", - Title = groupname, - Description = "by yubaolee" - }); - } + var groupname = GetSwaggerGroupName(controller); - logger.LogInformation($"api doc basepath:{AppContext.BaseDirectory}"); - foreach (var name in Directory.GetFiles(AppContext.BaseDirectory, "*.*", - SearchOption.AllDirectories).Where(f => Path.GetExtension(f).ToLower() == ".xml")) - { - option.IncludeXmlComments(name, includeControllerXmlComments: true); - // logger.LogInformation($"find api file{name}"); - } - - option.OperationFilter(); // 添加httpHeader参数 - - if (!string.IsNullOrEmpty(identityServer)) - { - //接入identityserver - option.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme - { - Type = SecuritySchemeType.OAuth2, - Description = "OAuth2登陆授权", - Flows = new OpenApiOAuthFlows + option.SwaggerDoc(groupname, new OpenApiInfo { - Implicit = new OpenApiOAuthFlow + Version = "v1", + Title = groupname, + Description = "by yubaolee" + }); + } + + logger.LogInformation($"api doc basepath:{AppContext.BaseDirectory}"); + foreach (var name in Directory.GetFiles(AppContext.BaseDirectory, "*.*", + SearchOption.AllDirectories).Where(f => Path.GetExtension(f).ToLower() == ".xml")) + { + option.IncludeXmlComments(name, includeControllerXmlComments: true); + // logger.LogInformation($"find api file{name}"); + } + + option.OperationFilter(); // 添加httpHeader参数 + + if (!string.IsNullOrEmpty(identityServer)) + { + //接入identityserver + option.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme + { + Type = SecuritySchemeType.OAuth2, + Description = "OAuth2登陆授权", + Flows = new OpenApiOAuthFlows { - AuthorizationUrl = new Uri($"{identityServer}/connect/authorize"), - Scopes = new Dictionary + Implicit = new OpenApiOAuthFlow { - {"openauthapi", "同意openauth.webapi 的访问权限"} //指定客户端请求的api作用域。 如果为空,则客户端无法访问 + AuthorizationUrl = new Uri($"{identityServer}/connect/authorize"), + Scopes = new Dictionary + { + {"openauthapi", "同意openauth.webapi 的访问权限"} //指定客户端请求的api作用域。 如果为空,则客户端无法访问 + } } } - } - }); - option.OperationFilter(); - } - }); + }); + option.OperationFilter(); + } + }); + } services.Configure(Configuration.GetSection("AppSetting")); services.AddControllers(option => { option.Filters.Add(); }) .ConfigureApiBehaviorOptions(options => @@ -270,34 +276,37 @@ namespace OpenAuth.WebApi //配置ServiceProvider AutofacContainerModule.ConfigServiceProvider(app.ApplicationServices); + // 只在开发环境中启用 Swagger 和 MiniProfiler if (env.IsDevelopment()) { app.UseMiniProfiler(); app.UseDeveloperExceptionPage(); app.UseSwagger(); + + // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), + // specifying the Swagger JSON endpoint. + app.UseSwaggerUI(c => + { + c.IndexStream = () => + IntrospectionExtensions.GetTypeInfo(GetType()).Assembly + .GetManifestResourceStream("OpenAuth.WebApi.index.html"); + + foreach (var controller in GetControllers()) + { + var groupname = GetSwaggerGroupName(controller); + + c.SwaggerEndpoint($"/swagger/{groupname}/swagger.json", groupname); + } + + c.DocExpansion(DocExpansion.List); //默认展开列表 + c.OAuthClientId("OpenAuth.WebApi"); //oauth客户端名称 + c.OAuthAppName("开源版webapi认证"); // 描述 + }); } - // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), - // specifying the Swagger JSON endpoint. - app.UseSwaggerUI(c => - { - c.IndexStream = () => - IntrospectionExtensions.GetTypeInfo(GetType()).Assembly - .GetManifestResourceStream("OpenAuth.WebApi.index.html"); - - foreach (var controller in GetControllers()) - { - var groupname = GetSwaggerGroupName(controller); - - c.SwaggerEndpoint($"/swagger/{groupname}/swagger.json", groupname); - } - - c.DocExpansion(DocExpansion.List); //默认展开列表 - c.OAuthClientId("OpenAuth.WebApi"); //oauth客户端名称 - c.OAuthAppName("开源版webapi认证"); // 描述 - }); + } ///