亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

c# webapi 配置swagger的方法

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

如何配置swagger?

在使用項(xiàng)目中,我們希望去查看我們的webapi的測(cè)試,那么我們是需要去有一個(gè)集成的測(cè)試的。

步驟

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

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

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

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

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

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

好吧,ok,我們知道了這個(gè)配置了。

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

4.那么接下來(lái)就是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中只能存在一個(gè)get,否則會(huì)報(bào)錯(cuò),因?yàn)樾枰蟫estful 標(biāo)準(zhǔn)。

一個(gè)controller中只能有一個(gè)HttpGet請(qǐng)求,多了就會(huì)報(bào)錯(cuò)。建議減少重載方法,將其他Get方法分開

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

另:可以不安裝swagger ui for .net,安了有可能會(huì)報(bào)錯(cuò)

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

相關(guān)文章

最新評(píng)論