SwaggerConfig.cs 17 KB

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