欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

c# webapi 配置swagger的方法

 更新時間:2020年07月09日 14:57:31   作者:團隊buff工具人  
這篇文章主要介紹了c# webapi 配置swagger的方法,文中示例代碼非常詳細,幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下

如何配置swagger?

在使用項目中,我們希望去查看我們的webapi的測試,那么我們是需要去有一個集成的測試的。

步驟

1.在nutget管理包中下載swagger包。

2.這樣會在App_start 文件夾中出現(xiàn)swaggerconfig.cs 和swaggerNet.cs,
這個時候就需要配置的時候了。

3.取消下面的注釋(swaggerconfig.cs)

 c.IncludeXmlComments(string.Format("{0}/bin/ThinkingSpace.XML", System.AppDomain.CurrentDomain.BaseDirectory));

當(dāng)然我們?yōu)榱舜a的模塊化,可以封裝到一個方法中:

private static string GetXmlCommentsPath()
{
  return $@"{System.AppDomain.CurrentDomain.BaseDirectory}\bin\GetDocumentation.XML";
}

好吧,ok,我們知道了這個配置了。

那么我們需要再bin目錄下創(chuàng)建一個xml,推薦是項目名.xml.

4.那么接下來就是swaggerNet.cs配置.

using System;
using System.IO;
using System.Web;
using System.Web.Http;
using System.Web.Http.Description;
using System.Web.Http.Dispatcher;
using System.Web.Routing;
using Swagger.Net;

[assembly: WebActivator.PreApplicationStartMethod(typeof(ThinkingSpace.App_Start.SwaggerNet), "PreStart")]
[assembly: WebActivator.PostApplicationStartMethod(typeof(ThinkingSpace.App_Start.SwaggerNet), "PostStart")]
namespace ThinkingSpace.App_Start 
{
  public static class SwaggerNet 
  {
    public static void PreStart() 
    {
      RouteTable.Routes.MapHttpRoute(
        name: "SwaggerApi",
        routeTemplate: "api/docs/{controller}",
        defaults: new { swagger = true }
      );      
    }
    
    public static void PostStart() 
    {
      var config = GlobalConfiguration.Configuration;

      config.Filters.Add(new SwaggerActionFilter());
      
      try
      {
        config.Services.Replace(typeof(IDocumentationProvider),
          new XmlCommentDocumentationProvider(HttpContext.Current.Server.MapPath("~/bin/ThinkingSpace.XML")));
      }
      catch (FileNotFoundException)
      {
        throw new Exception("Please enable \"XML documentation file\" in project properties with default (bin\\ThinkingSpace.XML) value or edit value in App_Start\\SwaggerNet.cs");
      }
    }
  }
}

統(tǒng)一我們需要修改xml的位置即可。

注意

我們需要在webapi中只能存在一個get,否則會報錯,因為需要符合restful 標(biāo)準(zhǔn)。

一個controller中只能有一個HttpGet請求,多了就會報錯。建議減少重載方法,將其他Get方法分開

如果在swagger.config中加上c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());則會只顯示第一個get方法

另:可以不安裝swagger ui for .net,安了有可能會報錯

以上就是c# webapi 配置swagger的方法的詳細內(nèi)容,更多關(guān)于c# 配置swagger的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論