上一步我们创建好CoreApi

接下来在框架中加入 Swagger  并发布  到 IIS

(1)首先点击依赖项》管理Nuget包

AspNet Core Api Restful +Swagger  发布IIS  实现微服务之旅   (二)

(2)输入 Swashbuckle.aspnetCore  比如:

AspNet Core Api Restful +Swagger  发布IIS  实现微服务之旅   (二)

图中两个Swagger 插件需要我们安装   注意:我这里已经安装过显示的是 卸载

 (3) 在框架中 添加Swagger 注解的帮助类   HttpHeaderOperation  下面是我完整的.CS文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;


//添加引用
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using Microsoft.AspNetCore.Authorization;
namespace WebCoreApi
{
    public class HttpHeaderOperation : IOperationFilter
    {
        /// <summary>
        /// 实现接口
        /// </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 actionAttrs = context.ApiDescription.ActionAttributes();

            var isAuthorized = actionAttrs.Any(a => a.GetType() == typeof(AuthorizeAttribute));

            if (isAuthorized == false) //提供action都没有权限特性标记,检查控制器有没有
            {
                var controllerAttrs = context.ApiDescription.ControllerAttributes();

                isAuthorized = controllerAttrs.Any(a => a.GetType() == typeof(AuthorizeAttribute));
            }

            var isAllowAnonymous = actionAttrs.Any(a => a.GetType() == typeof(AllowAnonymousAttribute));

            if (isAuthorized && isAllowAnonymous == false)
            {
                operation.Parameters.Add(new NonBodyParameter()
                {
                    Name = "Authorization",  //添加Authorization头部参数
                    In = "header",
                    Type = "string",
                    Required = false
                });
            }
        }
    }
}
View Code

相关文章:

  • 2021-12-02
  • 2022-02-12
  • 2021-04-11
  • 2021-09-23
  • 2022-12-23
  • 2021-06-21
  • 2021-10-29
猜你喜欢
  • 2022-02-09
  • 2021-06-17
  • 2021-12-20
  • 2022-01-22
  • 2021-06-23
相关资源
相似解决方案