[聚合文章] AspNet Core Api Restful +Swagger 发布IIS 实现微服务之旅 (二)

.Net 2017-12-19 41 阅读

上一步我们创建好CoreApi

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

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

(2)输入 Swashbuckle.aspnetCore  比如:

图中两个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                });
                

注:本文内容来自互联网,旨在为开发者提供分享、交流的平台。如有涉及文章版权等事宜,请你联系站长进行处理。