ios中amplify配置configure_Asp.netCore3.0 简单的webapi接口 (中)

增加接口文档

添加swagger包

打开程序包管理控制台,然后输入以下代码安装swagger包
Install-Package Swashbuckle.AspNetCore -Version 5.0.0-rc4

fb68151e8f5d78d72f8aebd045ef4eaa.png

安装swagger

通过Nuget包管理器安装swagger

d3dfe9bea9edc294997cf04562de1c07.png

安装完毕以后可以在包中看到Swashbuckle.AspNetCore5.0

69e67d22cb4f8fc54178691ad4a3721e.png

设置API输出XML文档文件

双击Properties,在打开的页面选择生成,按照红框内容配置xml文件输出

84e22be8718f20e9e72244299fd90a69.png
8516dd0a5416342ae5fe4be1ba0fc6ec.png

注册Swagger服务

打开XXX.api中Startup.cs文件,在ConfigureServices中注册Swagger服务

 // 用来向容器中注册服务,注册好的服务可以在其他地方进行调用        public void ConfigureServices(IServiceCollection services)        {            //数据库连接字符串            string conn = Configuration.GetConnectionString("xxxDB");            Models.XXXEntities.xxxContext.ConStr = conn;                        //注册swagger服务,定义1个或者多个swagger文档            services.AddSwaggerGen(s=> {                //设置swagger文档相关信息                s.SwaggerDoc("v1", new OpenApiInfo                {                    Title = "xxxWebApi文档",                    Description = "这是一个简单的NetCore WebApi项目",                    Version = "v1.0"                });                            //获取xml注释文件的目录                var xmlFile = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml";                var xmlPath = System.IO.Path.Combine(AppContext.BaseDirectory, xmlFile);                // 启用xml注释                s.IncludeXmlComments(xmlPath);            });            services.AddControllers();            services.AddRouting();            //services.AddDbContext(options =>            //{            //    options.UseSqlServer(conn);            //});        }

SwaggerDoc是配置Swagger文档相关属性的地方,比如名称、描述、版本等
IncludeXmlComments 设置第二步中xml文档文件路径

打开XXX.api中Startup.cs文件,在Configure中启用Swagger服务

 // 用来配置中间件管道,即如何响应http请求.        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)        {            if (env.IsDevelopment())            {                app.UseDeveloperExceptionPage();            }            else            {                app.UseExceptionHandler("api/Error");            }            app.UseRouting();            app.UseAuthorization();            //启用swagger中间件            app.UseSwagger(opt=> {                //opt.RouteTemplate = "api/{controller=Home}/{action=Index}/{id?}";            });            //启用SwaggerUI中间件(htlm css js等),定义swagger json 入口            app.UseSwaggerUI(s => {                                s.SwaggerEndpoint("/swagger/v1/swagger.json", "xxxWebapi文档v1");                //要在应用的根 (http://localhost:/) 处提供 Swagger UI,请将 RoutePrefix 属性设置为空字符串:                //s.RoutePrefix = string.Empty;            });            app.UseEndpoints(endpoints =>            {                //endpoints.MapControllerRoute(                //     name: "default",                //     pattern: "api/{controller}/{action}/{id?}");                endpoints.MapControllers();            });        }

如果想通过http://xxxx.com:的方式访问Swagger文档则添加RoutePrefix = string.Empty;即可

解决No operations defined in spec!问题

一般来说按照上面的方式配置好就可以访问Swagger文档了,但是最后还是出了“No operations defined in spec!”的问题

a4cfb1f46bd50d44f7c79b25f44ecec8.png

问题原因:在前面我们将路由配置统一从Controller中去掉然后endpoints.MapControllerRoute设置了路由模版,由于Swagger无法在Controller中找到[Route("api/[controller]/[action]")]和[ApiController]从而触发了“No operations defined in spec!”的问题。下图是我们注释的内容和增加的内容

df7f8ce623bcb02cd82a2e5545db4338.png
68bfa2cbe5e1ac99d937a203ec75eb7b.png

解决方案
.将Startup.cs中Configure里的路由模版注释掉,改成endpoints.MapControllers();然后在Controller里添加路由模版,或者将Startup.cs中Configure里的路由模版注释掉,改成endpoints.MapControllers();,增加BaseController.cs并继承ControllerBase,然后在BaseController设置路由模版,让Controller继承BaseController

BaseController.cs代码

using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNetCore.Mvc;namespace XXX.api{    ///     /// 自定义路由模版    /// 用于解决swagger文档No operations defined in spec!问题    ///     [Route("api/[controller]/[action]")]    [ApiController]    public class BaseController : ControllerBase    {    }}

解决CS1591警告

配置完Swagger以后出现了一个令人不爽的警告

db8f618d43a220e6d56669c0cfa19ee2.png
7549f815d6dcd30e42abc0d416c6e0ce.png

双击Properties

164edf4d73c7ad526519baf2037ba6cb.png

找到生成,定位到错误和警告

ff749258ef57b3d68ab7b6c8122cd133.png

新增取消显示警告1591

c6042a828cb0c79a6e108447cf985999.png
9f6350691cffa8b4b11277398b83e084.png

读取appsettings.json配置类

在appsettings.json文件中增加一个存放配置信息的参数AppSettings

{  "Logging": {    "LogLevel": {      "Default": "Information",      "Microsoft": "Warning",      "Microsoft.Hosting.Lifetime": "Information"    }  },  "AllowedHosts": "*",  //接口配置参数设置  "AppSettings": {    //数据库连接字符串    "xxxDB": "Server=127.0.0.1;User Id=用户id;Password=密码;Database=数据库名称;",    //接口是否需要签名    "IsSign": "true",    //16位MD5签名key    "Md5Key": "5ShiCeShiAAAAAAA"  }}

增加AppSettings.cs操作类

using Microsoft.Extensions.Configuration;using System;using System.Collections.Generic;using System.Text;namespace XXX.Common{    public class AppSettings    {        private static IConfigurationSection appSection = null;        ///         /// 获取配置文件        ///         ///         ///         public static string GetAppSeting(string key)        {            if (appSection.GetSection(key)!=null)            {                return appSection.GetSection(key).Value;            }            else            {                return "";            }        }        ///         /// 设置配置文件        ///         ///         public static void SetAppSetting(IConfigurationSection section)        {            appSection = section;        }    }}

修改Startup.cs

在Startup.cs中的Configure方法中获取appsettings.json值,代码如下

//从appsettings.json获取配置文件            Common.AppSettings.SetAppSetting(Configuration.GetSection("AppSettings"));

使用

通过Common.AppSettings.GetAppSeting("配置文件名")读取配置文件
示例:
从配置文件中读取连接字符串
打开XXXContext.cs在OnConfiguring方法中设置数据库连接字符串。

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)        {            if (!optionsBuilder.IsConfigured)            {                //通过配置文件操作类读取数据库连接字符串                optionsBuilder.UseSqlServer(Common.AppSettings.GetAppSeting("xxxDB"));            }        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值