c# webapi 配置swagger的方法
如何配置swagger?
在使用项目中,我们希望去查看我们的webapi的测试,那么我们是需要去有一个集成的测试的。
步骤
1.在nutget管理包中下载swagger包。
2.这样会在App_start文件夹中出现swaggerconfig.cs和swaggerNet.cs,
这个时候就需要配置的时候了。
3.取消下面的注释(swaggerconfig.cs)
c.IncludeXmlComments(string.Format("{0}/bin/ThinkingSpace.XML",System.AppDomain.CurrentDomain.BaseDirectory));
当然我们为了代码的模块化,可以封装到一个方法中:
privatestaticstringGetXmlCommentsPath()
{
return$@"{System.AppDomain.CurrentDomain.BaseDirectory}\bin\GetDocumentation.XML";
}
好吧,ok,我们知道了这个配置了。
那么我们需要再bin目录下创建一个xml,推荐是项目名.xml.
4.那么接下来就是swaggerNet.cs配置.
usingSystem;
usingSystem.IO;
usingSystem.Web;
usingSystem.Web.Http;
usingSystem.Web.Http.Description;
usingSystem.Web.Http.Dispatcher;
usingSystem.Web.Routing;
usingSwagger.Net;
[assembly:WebActivator.PreApplicationStartMethod(typeof(ThinkingSpace.App_Start.SwaggerNet),"PreStart")]
[assembly:WebActivator.PostApplicationStartMethod(typeof(ThinkingSpace.App_Start.SwaggerNet),"PostStart")]
namespaceThinkingSpace.App_Start
{
publicstaticclassSwaggerNet
{
publicstaticvoidPreStart()
{
RouteTable.Routes.MapHttpRoute(
name:"SwaggerApi",
routeTemplate:"api/docs/{controller}",
defaults:new{swagger=true}
);
}
publicstaticvoidPostStart()
{
varconfig=GlobalConfiguration.Configuration;
config.Filters.Add(newSwaggerActionFilter());
try
{
config.Services.Replace(typeof(IDocumentationProvider),
newXmlCommentDocumentationProvider(HttpContext.Current.Server.MapPath("~/bin/ThinkingSpace.XML")));
}
catch(FileNotFoundException)
{
thrownewException("Pleaseenable\"XMLdocumentationfile\"inprojectpropertieswithdefault(bin\\ThinkingSpace.XML)valueoreditvalueinApp_Start\\SwaggerNet.cs");
}
}
}
}
统一我们需要修改xml的位置即可。
注意
我们需要在webapi中只能存在一个get,否则会报错,因为需要符合restful标准。
一个controller中只能有一个HttpGet请求,多了就会报错。建议减少重载方法,将其他Get方法分开
如果在swagger.config中加上c.ResolveConflictingActions(apiDescriptions=>apiDescriptions.First());则会只显示第一个get方法
另:可以不安装swaggeruifor.net,安了有可能会报错
以上就是c#webapi配置swagger的方法的详细内容,更多关于c#配置swagger的资料请关注毛票票其它相关文章!