为C# ASP.NET Web API的Swagger添加认证UI及解决版本冲突
解决Swagger中添加Token认证UI及DocumentFilter版本冲突问题
看起来你遇到的核心问题是Swashbuckle版本不匹配导致的DocumentFilter配置错误,同时需要为Swagger添加Token获取和认证的UI支持。下面分步骤帮你解决:
1. 修正DocumentFilter的配置位置(版本适配)
你提到的swaggerUiconfig does not contain a definition for DocumentFilter错误,是因为在针对ASP.NET Web API的Swashbuckle版本中,DocumentFilter属于Swagger文档生成环节的配置,不是UI配置环节。正确的配置方式是在EnableSwagger的lambda表达式中添加,而非EnableSwaggerUi。
打开你的SwaggerConfig.cs,修改配置块如下:
using Swashbuckle.Swagger; using System.Web.Http; using System.Web.Http.Description; public class SwaggerConfig { public static void Register() { var thisAssembly = typeof(SwaggerConfig).Assembly; GlobalConfiguration.Configuration .EnableSwagger(c => { // 保留你已有的Swagger文档配置(比如标题、版本等) // 在这里添加你的DocumentFilter c.DocumentFilter<AuthTokenOperation>(); }) .EnableSwaggerUi(c => { // 这里是Swagger UI的专属配置,比如自定义样式、注入脚本等 }); } }
2. 优化AuthTokenOperation类的细节
建议调整你的AuthTokenOperation类,让参数更符合OAuth2密码模式的实际需求(将username和password设为必填,添加grant_type的默认值):
using Swashbuckle.Swagger; using System.Collections.Generic; using System.Web.Http.Description; public class AuthTokenOperation : IDocumentFilter { public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { swaggerDoc.paths.Add("/api/token", new PathItem { post = new Operation { tags = new List<string> { "Auth" }, summary = "获取访问Token(OAuth2密码模式)", consumes = new List<string> { "application/x-www-form-urlencoded" }, parameters = new List<Parameter> { new Parameter { type = "string", name = "grant_type", required = true, @in = "formData", @default = "password", // 默认设置为密码模式,无需手动输入 description = "认证类型,固定为password" }, new Parameter { type = "string", name = "username", required = true, @in = "formData", description = "登录用户名" }, new Parameter { type = "string", name = "password", required = true, @in = "formData", description = "登录密码" } }, responses = new Dictionary<string, Response> { { "200", new Response { description = "成功返回Token,格式:{access_token: '', token_type: 'Bearer', expires_in: ...}" } }, { "400", new Response { description = "用户名或密码错误" } } } } }); } }
3. 解决版本冲突问题
如果仍然提示找不到IDocumentFilter或DocumentFilter方法,按以下步骤排查:
- 确认NuGet包版本:你需要安装针对ASP.NET Web API的
Swashbuckle包(最新5.x版本,比如5.6.0),而非Swashbuckle.AspNetCore(那是给ASP.NET Core用的)。卸载错误的包,重新安装:Uninstall-Package Swashbuckle.AspNetCore -Force Install-Package Swashbuckle -Version 5.6.0 - 检查命名空间:确保你的
AuthTokenOperation类引用了正确的命名空间:using Swashbuckle.Swagger;和using System.Web.Http.Description;。
4. 添加Swagger UI的Token认证输入功能
完成上述配置后,你可以在Swagger中调用/api/token接口获取Token,但还需要添加一个输入框来输入Token,以便调用需要认证的接口。
步骤1:添加自定义JavaScript文件
在你的项目中创建一个名为swagger-javascript.js的文件,设置其生成操作为嵌入的资源,内容如下:
$(function () { // 初始化Bearer Token认证实例 var bearerAuth = new SwaggerClient.ApiKeyAuthorization("Authorization", "", "header"); window.swaggerUi.api.clientAuthorizations.add("Bearer", bearerAuth); // 隐藏默认ApiKey输入框,添加自定义Token输入框 $('#input_apiKey').hide(); const tokenInput = $('<div class="input"><label for="bearerToken">Bearer Token:</label><input placeholder="粘贴获取到的Token" id="bearerToken" type="text" style="width: 400px; margin-left: 10px;"/></div>'); tokenInput.insertAfter('#input_apiKey'); // 监听Token输入变化,自动更新认证信息 $('#bearerToken').on('input', function () { const tokenValue = $(this).val().trim(); if (tokenValue) { bearerAuth.apiKey = `Bearer ${tokenValue}`; window.swaggerUi.api.clientAuthorizations.add("Bearer", bearerAuth); } else { window.swaggerUi.api.clientAuthorizations.remove("Bearer"); } }); });
步骤2:在SwaggerConfig中注入脚本
修改EnableSwaggerUi的配置,注入这个JavaScript文件(注意替换成你的项目命名空间):
.EnableSwaggerUi(c => { // 注入自定义脚本,替换为你的项目命名空间 c.InjectJavaScript(thisAssembly, "YourProjectNamespace.swagger-javascript.js"); });
现在启动你的项目,打开Swagger UI:
- 你会看到新增的
Auth标签下的/api/token接口,调用它输入用户名密码即可获取Token。 - 在Swagger UI顶部会出现Token输入框,粘贴获取到的Token后,所有需要认证的接口都会自动带上
Authorization: Bearer {token}请求头。
内容的提问来源于stack exchange,提问作者Kemal AL GAZZAH




