1. 程式人生 > 實用技巧 >Swagger在.Net Core中的應用

Swagger在.Net Core中的應用

1、新建.net core專案。

2、NuGet安裝Swagger外掛“Swashbuckle.AspNetCore”。

3、Startup.cs中新增程式碼

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddSwaggerGen(m => {
                m.SwaggerDoc("v1", new OpenApiInfo { Title = "CoreWebApi", Version = "v1" });
            });
} // 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(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseSwagger(); // 配置SwaggerUI app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "CoreWebApi"); c.RoutePrefix = string.Empty; });
app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }

4、修改launchSetings.json

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:50770",
      "sslPort": 44326
    }
  },
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "http://localhost:50770",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "use64Bit": true
    },
    "WebApplication11": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "index.html",
"environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" }, "applicationUrl": "https://localhost:5001;http://localhost:5000" } } }

5、啟動專案時不選擇IIS,選擇專案名稱那個,啟動後可看到Swaggerl介面及各地址,並可測試。