首页 > 其他分享 >dotnet framework 4.7.2 webapi 配置的swagger添加登录验证

dotnet framework 4.7.2 webapi 配置的swagger添加登录验证

时间:2024-09-19 17:46:13浏览次数:8  
标签:webapi 4.7 Swagger option framework API Swashbuckle swagger your

项目是.net framework 4.7.2加 webapi 写的接口,使用Swashbuckle包添加的 swagger支持

 App_Start\SwaggerConfig.cs中加

c.CustomAsset("index", thisAssembly, "WebApi.Jwt.SwaggerExtensions.index.html", false);

  1 using System.Web.Http;
  2 using WebActivatorEx;
  3 using WebApi.Jwt;
  4 using Swashbuckle.Application;
  5 using System;
  6 using Swashbuckle.Swagger;
  7 using System.Linq;
  8 using System.IO;
  9 
 10 [assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]
 11 
 12 namespace WebApi.Jwt
 13 {
 14     public class SwaggerConfig
 15     {
 16         public static void Register()
 17         {
 18             var thisAssembly = typeof(SwaggerConfig).Assembly;
 19 
 20             GlobalConfiguration.Configuration
 21                 .EnableSwagger(c =>
 22                     {
 23                         // By default, the service root url is inferred from the request used to access the docs.
 24                         // However, there may be situations (e.g. proxy and load-balanced environments) where this does not
 25                         // resolve correctly. You can workaround this by providing your own code to determine the root URL.
 26                         //
 27                         //c.RootUrl(req => GetRootUrlFromAppConfig());
 28 
 29                         // If schemes are not explicitly provided in a Swagger 2.0 document, then the scheme used to access
 30                         // the docs is taken as the default. If your API supports multiple schemes and you want to be explicit
 31                         // about them, you can use the "Schemes" option as shown below.
 32                         //
 33                         //c.Schemes(new[] { "http", "https" });
 34 
 35                         // Use "SingleApiVersion" to describe a single version API. Swagger 2.0 includes an "Info" object to
 36                         // hold additional metadata for an API. Version and title are required but you can also provide
 37                         // additional fields by chaining methods off SingleApiVersion.
 38                         //
 39                         c.SingleApiVersion("v1", "WebApi.Jwt");
 40 
 41                         //这个是自定义的filter,判断方法是否添加头部token使用
 42                         c.OperationFilter<HttpAuthHeaderFilter>();
 43 
 44                         //解决同样的接口名 传递不同参数
 45                         //c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
 46                         //自定义provider,可以让Controller的注释也显示出来
 47                         //c.CustomProvider((defaultProvider) => new SwaggerCacheProvider(defaultProvider, string.Format("{0}/bin/EIP.API.XML", System.AppDomain.CurrentDomain.BaseDirectory)));
 48 
 49 
 50                         // If you want the output Swagger docs to be indented properly, enable the "PrettyPrint" option.
 51                         //
 52                         //c.PrettyPrint();
 53 
 54                         // If your API has multiple versions, use "MultipleApiVersions" instead of "SingleApiVersion".
 55                         // In this case, you must provide a lambda that tells Swashbuckle which actions should be
 56                         // included in the docs for a given API version. Like "SingleApiVersion", each call to "Version"
 57                         // returns an "Info" builder so you can provide additional metadata per API version.
 58                         //
 59                         //c.MultipleApiVersions(
 60                         //    (apiDesc, targetApiVersion) => ResolveVersionSupportByRouteConstraint(apiDesc, targetApiVersion),
 61                         //    (vc) =>
 62                         //    {
 63                         //        vc.Version("v2", "Swashbuckle Dummy API V2");
 64                         //        vc.Version("v1", "Swashbuckle Dummy API V1");
 65                         //    });
 66 
 67                         // You can use "BasicAuth", "ApiKey" or "OAuth2" options to describe security schemes for the API.
 68                         // See https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md for more details.
 69                         // NOTE: These only define the schemes and need to be coupled with a corresponding "security" property
 70                         // at the document or operation level to indicate which schemes are required for an operation. To do this,
 71                         // you'll need to implement a custom IDocumentFilter and/or IOperationFilter to set these properties
 72                         // according to your specific authorization implementation
 73 
 74                         //c.BasicAuth("basic")
 75                         //    .Description("Basic HTTP Authentication");
 76 
 77                         // NOTE: You must also configure 'EnableApiKeySupport' below in the SwaggerUI section
 78                         //c.ApiKey("apiKey")
 79                         //    .Description("API Key Authentication")
 80                         //    .Name("apiKey")
 81                         //    .In("header");
 82                         //
 83                         //c.OAuth2("oauth2")
 84                         //    .Description("OAuth2 Implicit Grant")
 85                         //    .Flow("implicit")
 86                         //    .AuthorizationUrl("http://petstore.swagger.wordnik.com/api/oauth/dialog")
 87                         //    //.TokenUrl("https://tempuri.org/token")
 88                         //    .Scopes(scopes =>
 89                         //    {
 90                         //        scopes.Add("read", "Read access to protected resources");
 91                         //        scopes.Add("write", "Write access to protected resources");
 92                         //    });
 93 
 94                         // Set this flag to omit descriptions for any actions decorated with the Obsolete attribute
 95                         //c.IgnoreObsoleteActions();
 96 
 97                         // Each operation be assigned one or more tags which are then used by consumers for various reasons.
 98                         // For example, the swagger-ui groups operations according to the first tag of each operation.
 99                         // By default, this will be controller name but you can use the "GroupActionsBy" option to
100                         // override with any value.
101                         //
102                         //c.GroupActionsBy(apiDesc => apiDesc.HttpMethod.ToString());
103 
104                         // You can also specify a custom sort order for groups (as defined by "GroupActionsBy") to dictate
105                         // the order in which operations are listed. For example, if the default grouping is in place
106                         // (controller name) and you specify a descending alphabetic sort order, then actions from a
107                         // ProductsController will be listed before those from a CustomersController. This is typically
108                         // used to customize the order of groupings in the swagger-ui.
109                         //
110                         //c.OrderActionGroupsBy(new DescendingAlphabeticComparer());
111 
112                         // If you annotate Controllers and API Types with
113                         // Xml comments (http://msdn.microsoft.com/en-us/library/b2s063f7(v=vs.110).aspx), you can incorporate
114                         // those comments into the generated docs and UI. You can enable this by providing the path to one or
115                         // more Xml comment files.
116                         //
117                         //c.IncludeXmlComments(GetXmlCommentsPath());
118                         c.IncludeXmlComments(GetXmlCommentsPath(thisAssembly.GetName().Name));
119 
120                         // Swashbuckle makes a best attempt at generating Swagger compliant JSON schemas for the various types
121                         // exposed in your API. However, there may be occasions when more control of the output is needed.
122                         // This is supported through the "MapType" and "SchemaFilter" options:
123                         //
124                         // Use the "MapType" option to override the Schema generation for a specific type.
125                         // It should be noted that the resulting Schema will be placed "inline" for any applicable Operations.
126                         // While Swagger 2.0 supports inline definitions for "all" Schema types, the swagger-ui tool does not.
127                         // It expects "complex" Schemas to be defined separately and referenced. For this reason, you should only
128                         // use the "MapType" option when the resulting Schema is a primitive or array type. If you need to alter a
129                         // complex Schema, use a Schema filter.
130                         //
131                         //c.MapType<ProductType>(() => new Schema { type = "integer", format = "int32" });
132 
133                         // If you want to post-modify "complex" Schemas once they've been generated, across the board or for a
134                         // specific type, you can wire up one or more Schema filters.
135                         //
136                         //c.SchemaFilter<ApplySchemaVendorExtensions>();
137 
138                         // In a Swagger 2.0 document, complex types are typically declared globally and referenced by unique
139                         // Schema Id. By default, Swashbuckle does NOT use the full type name in Schema Ids. In most cases, this
140                         // works well because it prevents the "implementation detail" of type namespaces from leaking into your
141                         // Swagger docs and UI. However, if you have multiple types in your API with the same class name, you'll
142                         // need to opt out of this behavior to avoid Schema Id conflicts.
143                         //
144                         //c.UseFullTypeNameInSchemaIds();
145 
146                         // Alternatively, you can provide your own custom strategy for inferring SchemaId's for
147                         // describing "complex" types in your API.
148                         //
149                         //c.SchemaId(t => t.FullName.Contains('`') ? t.FullName.Substring(0, t.FullName.IndexOf('`')) : t.FullName);
150 
151                         // Set this flag to omit schema property descriptions for any type properties decorated with the
152                         // Obsolete attribute
153                         //c.IgnoreObsoleteProperties();
154 
155                         // In accordance with the built in JsonSerializer, Swashbuckle will, by default, describe enums as integers.
156                         // You can change the serializer behavior by configuring the StringToEnumConverter globally or for a given
157                         // enum type. Swashbuckle will honor this change out-of-the-box. However, if you use a different
158                         // approach to serialize enums as strings, you can also force Swashbuckle to describe them as strings.
159                         //
160                         //c.DescribeAllEnumsAsStrings();
161 
162                         // Similar to Schema filters, Swashbuckle also supports Operation and Document filters:
163                         //
164                         // Post-modify Operation descriptions once they've been generated by wiring up one or more
165                         // Operation filters.
166                         //
167                         //c.OperationFilter<AddDefaultResponse>();
168                         //
169                         // If you've defined an OAuth2 flow as described above, you could use a custom filter
170                         // to inspect some attribute on each action and infer which (if any) OAuth2 scopes are required
171                         // to execute the operation
172                         //
173                         //c.OperationFilter<AssignOAuth2SecurityRequirements>();
174 
175                         // Post-modify the entire Swagger document by wiring up one or more Document filters.
176                         // This gives full control to modify the final SwaggerDocument. You should have a good understanding of
177                         // the Swagger 2.0 spec. - https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md
178                         // before using this option.
179                         //
180                         //c.DocumentFilter<ApplyDocumentVendorExtensions>();
181 
182                         // In contrast to WebApi, Swagger 2.0 does not include the query string component when mapping a URL
183                         // to an action. As a result, Swashbuckle will raise an exception if it encounters multiple actions
184                         // with the same path (sans query string) and HTTP method. You can workaround this by providing a
185                         // custom strategy to pick a winner or merge the descriptions for the purposes of the Swagger docs
186                         //
187                         //c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
188 
189                         // Wrap the default SwaggerGenerator with additional behavior (e.g. caching) or provide an
190                         // alternative implementation for ISwaggerProvider with the CustomProvider option.
191                         //
192                         //c.CustomProvider((defaultProvider) => new CachingSwaggerProvider(defaultProvider));
193                     })
194                 .EnableSwaggerUi(c =>
195                     {
196                         // Use the "DocumentTitle" option to change the Document title.
197                         // Very helpful when you have multiple Swagger pages open, to tell them apart.
198                         //
199                         //c.DocumentTitle("My Swagger UI");
200 
201                         // Use the "InjectStylesheet" option to enrich the UI with one or more additional CSS stylesheets.
202                         // The file must be included in your project as an "Embedded Resource", and then the resource's
203                         // "Logical Name" is passed to the method as shown below.
204                         //
205                         //c.InjectStylesheet(containingAssembly, "Swashbuckle.Dummy.SwaggerExtensions.testStyles1.css");
206                         //c.InjectStylesheet(thisAssembly, "/swagger/ui/swagger.css");
207                         //c.InjectJavaScript(thisAssembly, "/swagger/ui/swagger.js");
208 
209 
210                         c.CustomAsset("index", thisAssembly, "WebApi.Jwt.SwaggerExtensions.index.html", false);
211 
212 
213                         // Use the "InjectJavaScript" option to invoke one or more custom JavaScripts after the swagger-ui
214                         // has loaded. The file must be included in your project as an "Embedded Resource", and then the resource's
215                         // "Logical Name" is passed to the method as shown above.
216                         //
217                         //c.InjectJavaScript(thisAssembly, "Swashbuckle.Dummy.SwaggerExtensions.testScript1.js");
218 
219                         // The swagger-ui renders boolean data types as a dropdown. By default, it provides "true" and "false"
220                         // strings as the possible choices. You can use this option to change these to something else,
221                         // for example 0 and 1.
222                         //
223                         //c.BooleanValues(new[] { "0", "1" });
224 
225                         // By default, swagger-ui will validate specs against swagger.io's online validator and display the result
226                         // in a badge at the bottom of the page. Use these options to set a different validator URL or to disable the
227                         // feature entirely.
228                         //c.SetValidatorUrl("http://localhost/validator");
229                         //c.DisableValidator();
230 
231                         //c.SetValidatorUrl("http://localhost:39051/demo.html");
232 
233                         // Use this option to control how the Operation listing is displayed.
234                         // It can be set to "None" (default), "List" (shows operations for each resource),
235                         // or "Full" (fully expanded: shows operations and their details).
236                         //
237                         //c.DocExpansion(DocExpansion.List);
238 
239                         // Specify which HTTP operations will have the 'Try it out!' option. An empty paramter list disables
240                         // it for all operations.
241                         //
242                         //c.SupportedSubmitMethods("GET", "HEAD");
243 
244                         // Use the CustomAsset option to provide your own version of assets used in the swagger-ui.
245                         // It's typically used to instruct Swashbuckle to return your version instead of the default
246                         // when a request is made for "index.html". As with all custom content, the file must be included
247                         // in your project as an "Embedded Resource", and then the resource's "Logical Name" is passed to
248                         // the method as shown below.
249                         //
250                         //c.CustomAsset("index", containingAssembly, "YourWebApiProject.SwaggerExtensions.index.html");
251 
252                         // If your API has multiple versions and you've applied the MultipleApiVersions setting
253                         // as described above, you can also enable a select box in the swagger-ui, that displays
254                         // a discovery URL for each version. This provides a convenient way for users to browse documentation
255                         // for different API versions.
256                         //
257                         //c.EnableDiscoveryUrlSelector();
258 
259                         // If your API supports the OAuth2 Implicit flow, and you've described it correctly, according to
260                         // the Swagger 2.0 specification, you can enable UI support as shown below.
261                         //
262                         //c.EnableOAuth2Support(
263                         //    clientId: "test-client-id",
264                         //    clientSecret: null,
265                         //    realm: "test-realm",
266                         //    appName: "Swagger UI"
267                         //    //additionalQueryStringParams: new Dictionary<string, string>() { { "foo", "bar" } }
268                         //);
269 
270                         // If your API supports ApiKey, you can override the default values.
271                         // "apiKeyIn" can either be "query" or "header"
272                         //
273                         //c.EnableApiKeySupport("apiKey", "header");
274                     });
275         }
276 
277 
278         //private static string GetXmlCommentsPath()
279         //{
280         //    return string.Format("{0}/bin/WebApi.XML", System.AppDomain.CurrentDomain.BaseDirectory);
281         //}
282         protected static string GetXmlCommentsPath(string name)
283         {
284             return System.String.Format(@"{0}\bin\{1}.xml", System.AppDomain.CurrentDomain.BaseDirectory, name);
285         }
286 
287     }
288 }
View Code

这时配置好,可以通过http://localhost:39051/swagger/ui/index 访问到swagger文档,右键查看源代码,抄下来

添加index.html,粘贴源代码,再在每个资源文件,js,css 前面加上路径前缀,像这样

 成功:

然后在这个页面上能想干啥干啥了吧

 

标签:webapi,4.7,Swagger,option,framework,API,Swashbuckle,swagger,your
From: https://www.cnblogs.com/yansc/p/18421067

相关文章

  • 【转】[C#] WebAPI 防止并发调用二(更多)
    转自:阿里的通义灵码接上篇:https://www.cnblogs.com/z5337/p/18181574在C#中防止接口的并发访问(即确保同一时间内只有一个线程能够访问某个资源或方法),可以通过多种方式实现。这里列出一些常见的方法:1.使用 lock 语句lock 是一种常用的同步原语,用于保护对共享资源的访问......
  • DevExpress中文教程:如何将WinForms数据网格连接到ASP. NET Core WebAPI服务?
    日前DevExpress官方发布了DevExpressWinForms的后续版本——将.NET桌面客户端连接到安全后端WebAPI服务(EFCorewithOData),在本文中我们将进一步演示如何使用一个更简单的服务来设置DevExpressWinForms数据网格。P.S:DevExpressWinForms拥有180+组件和UI库,能为WindowsForms......
  • .NET Standard/.NET Framework/.NET Core/ASP.NET/ASP.NET Core/ASP.NET MVC/ADO.NET
    这是常识.......就算名字取得再混乱名字角色简介.NETStandard规范一种跨平台的API规范,它定义了一组共同的类库和框架特性.NETFramework框架 Windows 平台的框架.NETCore框架开源、跨平台的框架ASP.NET框架在.NETFramework上构建的,专注于传统的Web服务器端开发ASP.NET......
  • 当前标识(IIS APPPOOL\.NET v4.5)没有对“C:\Windows\Microsoft.NET\Framework64
    当前标识(IISAPPPOOL\.NETv4.5)没有对“C:\Windows\Microsoft.NET\Framework64\v4.0.30319\TemporaryASP.NETFiles”的写访问权限。初学者在使用ISS创建网站时是不是也遇到过类似的问题,这可能是执行当前Web请求期间生成了未经处理的异常,主要就是设置对TemporaryASP.NE......
  • 自动化测试 RobotFramework-ride使用相关总结
    开发环境win11家庭中文版Python3.9.13robotframework6.1.1说明:为了方便的使用robot命令,安装好robotframwork后,修改系统环境,添加robot.exe(PYTHON_HOME/Scripts/robot.exe)所在路径到系统环境变量path安装参考连接:https://github.com/robotframework/robotframework/blob/mast......
  • Metasploit Framework (MSF) 使用指南 - 第一篇:介绍与基础用法
    引言MetasploitFramework(MSF)是一款功能强大的开源安全漏洞检测工具,被广泛应用于渗透测试中。它内置了数千个已知的软件漏洞,并持续更新以应对新兴的安全威胁。MSF不仅限于漏洞利用,还包括信息收集、漏洞探测和后渗透攻击等多个环节,因此被安全社区誉为“可以黑掉整个宇宙”的工具。......
  • macOS Sonoma 14.7 (23H124) 正式版发布,ISO、IPSW、PKG 下载
    macOSSonoma14.7(23H124)正式版发布,ISO、IPSW、PKG下载2024年9月17日凌晨1点,TimCook领导的Apple今天发布了macOS15Sequoia正式版,iPhone镜像、密码应用程序、窗口平铺更新等带来全新体验。Apple还为那些无法升级到Sequoia的用户发布了macOSVentura13.7......
  • Comparing Multi-agent AI frameworks
    ComparingMulti-agentAIframeworkshttps://sajalsharma.com/posts/overview-multi-agent-fameworks/AComparativeOverviewTobetterunderstandthedifferencesandapplicationsoftheseframeworks,let’sexaminetheminacomparativetable:FeatureAutoGe......
  • Mastering openFrameworks_第四章_图片和纹理
    图片和纹理仅仅使用基本的几何元素来创建丰富的可视化效果通常是不够的。图像是帮助增加装饰,风格,甚至照片现实主义到一个互动场景的积木。在本章中,我们将介绍可以在图像上执行的基本操作:加载和绘制图像旋转图像色彩调制透明度创建和修改图像使用ofTexture进行内存优化......
  • Mastering openFrameworks_第五章_使用视频
    使用视频使用视频镜头是一种简单的方式来添加动态图层的交互式项目场景。而视频处理是现代计算机视频艺术的基础。本章将涵盖openFrameworks项目中播放、分层和处理视频的基本和高级主题:播放视频文件处理视频帧径向和水平狭缝扫描效果正在处理来自摄像机的实时视频视频......