Swagger framework built from scratch twelve separate front and rear end NetCore2.2 (EF Core CodeFirst + Autofac) + Vue item (parameter) using the binary

  introduction

  In the previous mentioned in the basic use of Swagger is limited to no arguments, no verify the kind of document generation api, then this article will continue connect, interface generally has verified security, permissions, etc. in,

  Will add requester keys, signatures in the header / url, of course, also possible to add to the other parts of body, etc.,  Swashbuckle.AspNetCore  support these written.

  How to use - Here are two ways to use

Where two modes are provided to the parameter in   In attributes , the attribute for the following values: reference https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#parameter-object

  • query: field value corresponding to the parameter in the url
  • header: corresponding parameter values ​​in the header param
  • body: the parameters corresponding to the request body into
  • path: the path into the request parameter should correspond to specific seemingly useless @
  • formData: parameter corresponding to the request into a form

  The first: one or more parameters of the protected API "securityDefinitions" added to Swagger generated.

This was added directly to a document in the upper right  Authorize  button, a value is set, each request together with the corresponding values are provided at a position on an essay on the  ConfigureServices  process,

Corresponding position  services.AddSwaggerGen (options => {})  in   XmlComments   added under code is as follows:

                options.AddSecurityDefinition("token", new ApiKeyScheme
                {
                    The Description = " token the format: {} token " , // Parameter Description 
                    the Name = " token " , // the name of 
                    the In = " header " , // corresponding position 
                    the Type = " the apiKey " // Type Description 
                });
                options.AddSecurityDefinition("sid", new ApiKeyScheme
                {
                    The Description = " SID the format: {SID} " , // Parameter Description 
                    the Name = " SID " , // the name of 
                    the In = " header " , // corresponding position 
                    the Type = " the apiKey " // Type Description 
                });
                 // add Jwt verify the global settings, or not taken in the code 
                options.AddSecurityRequirement ( new new the Dictionary < String , the IEnumerable < String >> {
                    { "token", Enumerable.Empty<string>() },
                    { "sid", Enumerable.Empty<string>() },
                });

  After the addition is complete, run up and look effect, renderings: 

 Is provided on the corresponding values, invoke the test method may be taken to the newly set to a value in the header,

 Here you can see, the parameter set can take up. As a result, on the need to verify the interface, we can test through the interface documentation. With postman and so do not have the basic interface test tool.

But, however, there is a problem, that is, as long as the value of the parameter set, will bring each access parameters in the request.

A second embodiment will be described below, only to add authentication parameters need to verify the user interface.

  Second: the use of "filters" Extended Swagger generator add parameters to achieve only need to add on the method parameters. Complex can add the corresponding parameters according to their needs

Implementation is to first create a new class name:  SwaggerParameter  , implement  IOperationFilter  interface. SwaggerParameter  class code as follows: 

    /// <summary>
    /// 自定义添加参数
    /// </summary>
    public class SwaggerParameter : IOperationFilter
    {
        /// <summary>
        /// 实现 Apply 方法
        /// </summary>
        /// <param name="operation"></param>
        /// <param name="context"></param>
        public void Apply(Operation operation, OperationFilterContext context)
        {
            if (operation.Parameters == null) operation.Parameters = new List<IParameter>();
            var attrs = context.ApiDescription.ActionDescriptor.AttributeRouteInfo;
            var t = typeof(BaseUserController);
            //先判断是否是继承用户验证类
            if (context.ApiDescription.ActionDescriptor is ControllerActionDescriptor descriptor && context.MethodInfo.DeclaringType?.IsSubclassOf(t) == true)
            {
                //再验证是否允许匿名访问
                var actionAttributes = descriptor.MethodInfo.GetCustomAttributes(inherit: true);
                bool isAnonymous = actionAttributes.Any(a => a is AllowAnonymousAttribute);
                // 需要验证的方法添加
                if (!isAnonymous)
                {
                    operation.Parameters.Add(new NonBodyParameter()
                    {
                        Name = "sid",
                        In = "header", //query header body path formData
                        Type = "string",
                        Required = true,//是否必选
                        Description = "登录返回的sid"
                    });
                    operation.Parameters.Add(new NonBodyParameter()
                    {
                        Name = "token",
                        In = "header", //query header body path formData
                        Type = "string",
                        The Required = to true , // whether mandatory 
                        the Description = " token returned from login "
                    });
                }
            }
        }
    }

 After running, go to  https: // localhost: 5001 / apidoc / index.html  document pages, you can see the upper right corner of the  Authorize  button has disappeared, in not requiring authentication methods, can not find a corresponding need to set parameters input box. Only only on the need to verify the interface.

Referring to FIG Swagger following documents: 

Reference code is as follows:

 

Renderings: 

  Such a setting is finished. Can be seen from the above, the user only needs to verify will have corresponding interface parameters. 

 

My way is to set up a user-defined validation controller class, allowing the user to verify the controller needs to inherit the controller and do not need to add user authentication on the interface of the controller  AllowAnonymous  property 

It can be carried out to determine whether the need to add parameters according to the above-mentioned two points when setting fitter, if not realized, can change the fitter classes according to their needs, to control the generated document. 

 

If there is nothing wrong or above areas for improvement, I hope you noted or comments, discuss with learning ~ 

There need the source code can be obtained by this  GitHub  link pull think you can give a start and a point below the recommended oh ~ ~ Thank you!

Guess you like

Origin www.cnblogs.com/levywang/p/coreframe_12.html