使用Swagger服務搭建.Net Core API


使用Swagger服務搭建.Net Core API

創建.Net Core API

新建項目。文件——新建——項目

 

 

 

選擇應用程序模板。

設置存放路徑,命名方案名稱。

 

 

創建API。

 

 

 

搭建成功。

 

 

 

使用Swagger服務

添加引用

右鍵依賴項

 

 

 

搜索服務並安裝。安裝好之后,在NuGet下會新增該包。

 

 

在Startup.cs下的ConfigureServices方法中添加服務。

 

 

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                // c.IncludeXmlComments(xmlPath);
            });
        }

 

在Startup.cs類下的Configure方法中使用服務。

 

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseSwagger();
            //啟用中間件服務對swagger-ui,指定Swagger JSON終結點
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });
            app.UseHttpsRedirection();
            app.UseMvc();
        }

 

最后修改Properties文件夾下的launchSettings.json文件

 

 

運行成功。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM