一、背景
最近重构了公司一个老接口项目,弃用了原来的webservice服务,新项目用webapi写的。所以就有了 《Swagger使用的奇淫技巧》这篇文章。常规使用的技巧我这里就不在多赘述了,很多老鸟写的已经很详细了。这里我主要介绍下怎么使用VS remark 写MarkDown并且使用Swagger显示
二、ToDo
新建一个WEB API项目,项目名称Demo
引入Swagger
Install-Package Swashbuckle -ProjectName Demo -Version 5.6.0
右键Demo项目-->生成-->勾选xml文档文件,ctrl+s保存
打开App_Start文件夹,打开SwaggerConfig文件
添加方法GetXmlCommentsPath,并且打开c.IncludeXmlComments(GetXmlCommentsPath()); 这个配置
public static string GetXmlCommentsPath()
{
#if DEBUG
return AppDomain.CurrentDomain.BaseDirectory + "\\\\bin\\\\demo.xml";#elif RELEASE
return AppDomain.CurrentDomain.BaseDirectory + "\\\\bin\\\\Release\\\\demo.xml";
#else
return AppDomain.CurrentDomain.BaseDirectory + "\\\\bin\\\\demo.xml";
#endif
}
- 打开App_Start文件夹,新建文件 FormatCommentProperties.cs,并引入Swashbuckle.Swagger 类库 ,并在SwaggerConfig文件中添加新指向XML描述过滤c.OperationFilter
public class FormatCommentProperties : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
operation.description = Formatted(operation.description);
operation.summary = Formatted(operation.summary);
}
private string Formatted(string text)
{
if (text == null) return null;
// Strip out the whitespace that messes up the markdown in the xml comments,
// but don‘t touch the whitespace in <code> blocks. Those get fixed below.
string resultString = Regex.Replace(text, @"(^[ \\t]+)(?![^<]*>|[^>]*<\\/)", "", RegexOptions.Multiline);
resultString = Regex.Replace(resultString, @"<code[^>]*>", "``` C#", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline);
resultString = Regex.Replace(resultString, @"</code[^>]*>", "```", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline);
resultString = Regex.Replace(resultString, @"<!--", "", RegexOptions.Multiline);
resultString = Regex.Replace(resultString, @"-->", "", RegexOptions.Multiline);
try
{
string pattern = @"```(.*?)```";
foreach (Match match in Regex.Matches(resultString, pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline))
{
var formattedPreBlock = FormatPreBlock(match.Value);
resultString = System.Web.HttpUtility.htmlDecode(resultString.Replace(match.Value, formattedPreBlock));
}
return resultString;
}
catch
{
// Something went wrong so just return the original resultString
return resultString;
}
}
private string FormatPreBlock(string preBlock)
{
// Split the <pre> block into multiple lines
var linesArray = preBlock.Split(‘\\n‘);
if (linesArray.Length < 2)
{
return preBlock;
}
else
{
// Get the 1st line after the <pre>
string line = linesArray[1];
int lineLength = line.Length;
string formattedLine = line.TrimStart(‘ ‘, ‘\\t‘);
int paddingLength = lineLength - formattedLine.Length;
// Remove the padding from all of the lines in the <pre> block
for (int i = 1; i < linesArray.Length - 1; i++)
{
linesArray[i] = linesArray[i].Substring(paddingLength);
}
var formattedPreBlock = string.Join("", linesArray);
return formattedPreBlock;
}
}
}
写注释
现在启动站点