In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what is the process of .NetCore using Swagger+API multi-version control". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the process of .NetCore using Swagger+API multi-version control".
The example environment and version of this article. NetCore 3.1, Swagger6.1
Most of the current development is a separate mode of front and back end, with the back end providing the interface and the front end calling the interface. The backend provides interfaces that need to be tested, previously using browser developer tools, or writing unit tests, or directly using Postman, but now these are all out. The backend provides an interface, so how to cooperate with the front end to explain the nature of the interface, parameters and so on is also a problem. Is there a tool that can automatically generate interface documents according to the back-end interface, explain the nature of the interface, parameters and other information, but also provide interface calls and other related functions? The answer is yes. Swagger is a specification and complete framework for generating, describing, invoking, and visualizing RESTful-style Web services. As a. Net core development, Swashbuckle is the first choice for swagger applications!
The overall goal is to have the client and the file system update at the same speed as the server. The file's methods, parameters, and models are tightly integrated into the server-side code, allowing API to always keep synchronized. Swagger makes it easier for deployments to manage and use powerful API.
The entire swagger page access process is as follows:
1. The browser enters the swaggerUI page address, such as http://localhost:5000/swagger/index.html, which is configurable.
2. The request is intercepted by SwaggerUI middleware and then returns to the page, which is an embedded resource file or can be set to your own external page file (using external static file interception)
3. After receiving the Index page of Swagger, the page will load the first document, that is, get the document schema information swagger.json, according to the list of documents set by the SwaggerEndpoint method in SwaggerUI middleware.
4. The swagger.json requested by the browser is intercepted by Swagger middleware, then all the interfaces belonging to the request document are parsed, and finally a string of data in json format is returned.
5. The browser presents the UI interface according to the swagger,json data received.
1. Basic use of Swagger
1. Create a new NetCore project, add related Controller and add reference Swashbuckle.AspNetCore.Swagger
2. Add configuration to Startup
Inject Swashbuckle service into ConfigureServices
Services.AddSwaggerGen (c = > {c.SwaggerDoc ("V1", new OpenApiInfo {/ / version Version = "V1", / / title Title = $"Interface document-NetCore3.1", / / description Description = $"NetCore Http API v1", / / contact Contact = new OpenApiContact {Name = "Test", Email = "" Url = new Uri ("https://www.cnblogs.com/mzflog/")}, License = new OpenApiLicense {Name =" Test 2 ", Url = new Uri (" https://www.cnblogs.com/mzflog/")}})) / / load XML comment c.IncludeXmlComments (XmlCommentsFilePath);})
Add XmlCommentsFilePath attribute. You need to refer to Microsoft.Extensions.PlatformAbstractions at this time.
/ get the XML file of the current project name / static string XmlCommentsFilePath {get {var basePath = PlatformServices.Default.Application.ApplicationBasePath; var fileName = typeof (Startup). GetTypeInfo (). Assembly.GetName (). Name + ".xml"; return Path.Combine (basePath, fileName);}}
Add Swagger middleware UseSwagger,UseSwaggerUI to Configure
UseSwagger: add Swagger middleware, which is mainly used to intercept swagger.json requests so that you can get the interface architecture information you need to return.
UseSwaggerUI: add SwaggerUI middleware, which is mainly used to intercept swagger/index.html page requests and return the page to the front end.
App.UseSwagger (); app.UseSwaggerUI (c = > {c.SwaggerEndpoint ($"/ swagger/V1/swagger.json", $"NetCore V1"); / / c.RoutePrefix = string.Empty / / if the access path is empty, it is the root domain name / index.html. Note that localhost:8001/swagger is not accessible / / path configuration is set to empty, which means that the file c.RoutePrefix = "swagger" is accessed directly in the root domain name (localhost:8001); / / if you want to change the path, just write the name directly, such as c.RoutePrefix = "swagger". The access path is the root domain name / swagger/index.html})
Right-click the project properties to add XML to the build
Access is now available via http://localhost: port number / swagger
II. Swagger combined with version control
Benefits of versioning:
1. Help to launch functions in a timely manner without damaging the existing system.
2. It can also help provide additional features for selected customers.
1. Add references to Microsoft.AspNetCore.Mvc.Versioning and Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer. This article uses version 4.1.0.
2. In ConfigureServices
Services.AddApiVersioning (option = > {/ / optional, API returns supported version information option.ReportApiVersions = true; / / default is 1.0 option.DefaultApiVersion = new ApiVersion (1,0) when no version is specified in the request; / / what form the version number is in, and what field passes option.ApiVersionReader = ApiVersionReader.Combine (new HeaderApiVersionReader ("api-version")) / / if the version number is not provided, the default is 1.0If this configuration is not added, the error "message" will be reported if the version number is not provided: "An API version is required, but was not specified." / / option.AssumeDefaultVersionWhenUnspecified = true; / / access with the current highest version by default / / option.ApiVersionSelector = new CurrentImplementationApiVersionSelector (option) }) .AddVersionedApiExplorer (opt = > {/ / notify swagger to replace the version in the controller route and configure the format of the api version opt.SubstituteApiVersionInUrl = true; / / version name: v + version number opt.GroupNameFormat = "'v'VVV"; / / whether or not to provide API version service opt.AssumeDefaultVersionWhenUnspecified = true;}) / / method 1 (not recommended) warning that ASP0000 calling "BuildServiceProvider" from application code will result in the creation of an additional copy of the singleton service. Consider alternatives, such as using the dependency injection service as the "configuration" parameter services.AddSwaggerGen (options = > {/ / parsing the IApiVersionDescriptionProvider service var provider = services.BuildServiceProvider (). GetRequiredService (); / / adding a swagger document for each discovered version of foreach (var description in provider.ApiVersionDescriptions) {options.SwaggerDoc (description.GroupName, CreateInfoForApiVersion (description)) that does not need to be recorded) } / / load XML comments and enable the controller's comment information: false does not enable options.IncludeXmlComments (XmlCommentsFilePath,true) by default; / / method 2 (recommended) services.AddSwaggerGen (); / / resolve the scheme services.AddOptions () .configure ((options, service) = > {options.ResolveConflictingActions (apiDescriptions = > apiDescriptions.First ()) that reports the ASP0000 warning above / / add document information foreach (var item in service.ApiVersionDescriptions) {options.SwaggerDoc (item.GroupName, CreateInfoForApiVersion (item));} / / add filter / / options.OperationFilter () to swagger; / / load XML comment options.IncludeXmlComments (XmlCommentsFilePath, true) })
Add CreateInfoForApiVersion method
Static OpenApiInfo CreateInfoForApiVersion (ApiVersionDescription description) {var info = new OpenApiInfo () {/ / title Title = $".NET Core API for Test Project {description.ApiVersion}", / / current version Version = description.ApiVersion.ToString (), / / documentation Description = "current environment of the api project -" + EnvironmentName / / contact information Contact = new OpenApiContact () {Name = "title", Email = "", Url = null}, TermsOfService = new Uri (""), / / license License = new OpenApiLicense () {Name = "documentation", Url = new Uri (")}} / / message if (description.IsDeprecated) {info.Description + = "- this version has abandoned compatibility" when there is a deprecation mark;} return info;}
3. Add to Configure
IApiVersionDescriptionProvider: API version descriptor provider for enumerating defined API versions
Public void Configure (IApplicationBuilder app, IWebHostEnvironment env, IApiVersionDescriptionProvider provider)
/ / add Swagger middleware, which is mainly used to intercept swagger.json requests, so that you can get the required interface architecture information app.UseSwagger (opt = > {/ / routing template, the default is / swagger/ {documentName} / swagger.json, this attribute is very important! And this property must contain the {documentName} parameter. / / opt.RouteTemplate= "/ swagger/ {documentName} / swagger.json"; / / means to serialize and generate swagger.json in Swagger2.0 format. This is not recommended. You can use a new version as much as possible / / opt.SerializeAsV2}) / / add SwaggerUI middleware, mainly used to intercept swagger / index.html page requests, return the page to the front-end app.UseSwaggerUI (options = > {/ / create a JSON foreach (var description in provider.ApiVersionDescriptions) for each version) {/ / this attribute is to add our own code to the head tag of the SwaggerUI page, such as introducing some style files Or execute some of your own script code / / options.HeadContent + = $"alert ('Welcome to the SwaggerUI page')" / / display the drop-down version information displayed in the default header / / options.SwaggerEndpoint ($"/ swagger/ {description.GroupName} / swagger.json", description.GroupName.ToUpperInvariant ()); / / freely specify the drop-down version content options.SwaggerEndpoint ($"/ swagger/ {description.GroupName} / swagger.json", "coreApi" + description.ApiVersion) displayed in the default header. / / if the access path is empty, it is the root domain name / index.html. Note that localhost:8001/swagger is not accessible / / options.RoutePrefix = string.Empty; / / if you want to change the path, just write the name directly, such as c.RoutePrefix = "swagger"; then the access path is the root domain name / swagger/index.html options.RoutePrefix = "swagger". })
4. Add a version to the Controller of api
[ApiVersion ("1. 0", Deprecated = false)] / / whether this version is deprecated or not deprecated by default is false. This interface will still be displayed even if it is marked to deactivate, just as a hint that this version will be deprecated. [Route ("api/ [controller]")] [ApiController] / / [ApiExplorerSettings (IgnoreApi = true)] hides the interface Controller public class ValuesController: Controller [Obsolete] / / discards the Action method [ApiExplorerSettings (IgnoreApi = true)] / / hides the Action method public IEnumerable Get ()
Create a new controller and add [ApiVersion ("2.0")] to experience version control
When you visit the page, you can select different versions in the drop-down box on the right, which will show the controllers under different versions.
Thank you for reading, the above is the content of "what is the process of .NetCore using Swagger+API multi-version control". After the study of this article, I believe you have a deeper understanding of what the process of .NetCore using Swagger+API multi-version control is, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.