栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

使用.NET 5搭建ASP.NET Core Web Api项目使用swagger

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用.NET 5搭建ASP.NET Core Web Api项目使用swagger

在ASP.NET Core WebApi空项目搭建Swagger

开发工具:Visual Studio 2019

第一步创建一个ASP.NET Core WebApi的项目

第二步设置它的目标框架和取消一些默认配置

(在这里当我们进入到这个页面时,下面的配置有的会默认选中,我为了不影响后期的开发就把所有的默认选中全部取消了)

第三步成功创建项目(当我们创建项目成功之后,点击运行发现并不是我们想要的页面,它返回的似乎一串json字符串)


第四步添加我们的Swagger配置(右键项目->管理nuget包->选择Swashuckle.AspNetCore)



第五步我们成功添加netget包之后,在startup类中添加配置文件

代码如下

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace JMP.Api
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //注册Swagger生成器,定义一个或多个Swagger文件
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
                {
                    Title = "JMP Api",
                    Version = "v1"
                });
            });
            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            //启用中间件Swagger()
            app.UseSwagger();
            //启用中间件Swagger()的UI服务,他需要与Swagger()配置在一起
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "JMP Api V1");
            });
            app.UseRouting();
            //添加授权中间件
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

第六步运行项目,发现页面还是和之前的一样,这时我们需要自己重定向到‘/swagger/index.html’

这时我们的项目就出来,但是呢?有一个问题,这样每次运行都需要自己手动修改重定向到那个页面,这样岂不是非常麻烦,我这个人最讨厌麻烦了,所以我们需要修改一下它的默认路径。

第七步右键项目的属性(注意:这里右键的是你自己创建的项目的属性,不是解决方案的属性,与上面的是一样的),然后点击进入调试页面


然后将里面的代码替换成我们自己的路径,然后保存,点击运行就成功啦

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/908226.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号