asp.netasp.net-coreswaggerswagger-uiswashbuckle

How to handle <see /> XML documentation tags in Swagger?


I have an ASP.Net Web API with XML documentation throughout, including many <see /> tags.

I've recently added Swagger (Swashbuckle UI stuff) to the solution, and noticed that it doesn't handle XML tags like <see />. After looking around online I found this - https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/57, so it seems like the devs don't want to fix this.

Does anybody have any suggestions? I tried running a little .exe to replace all tags in the generated XML file with their object names (e.g. <see cref="MyObject"/> becomes MyObject), but this kept screwing up and even when I did it manually Swagger for some reason didn't pick up the changes (is the XML loaded into memory somewhere?)


Solution

  • Following on from Kit's suggestion, I found a way to retrieve and change the documentation, but needed a way to parse XML tags. I found this which, although it refers to HTML, removes XML tags just as well.

    So, in the order they are required:

    1. I have a common Utilities class where I put the above HtmlAgilityPack code (though I called the method RemoveXMLTags)
    2. Added a new XmlDocumentFilter class as below:
    public class XmlDocumentFilter : IDocumentFilter
    {
        public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
        {
            foreach (var path in swaggerDoc.Paths)
            {
                foreach (var operation in path.Value.Operations)
                {
                    operation.Value.Description = Utilities.RemoveXMLTags(operation.Value.Description);
    
                    operation.Value.Summary = Utilities.RemoveXMLTags(operation.Value.Summary);
    
                    if (operation.Value.RequestBody != null)
                    {
                        operation.Value.RequestBody.Description = Utilities.RemoveXMLTags(operation.Value.RequestBody.Description);
                    }
    
                    foreach (var parameter in operation.Value.Parameters)
                    {
                        parameter.Description = Utilities.RemoveXMLTags(parameter.Description);
                    }
                }
            }
        }
    }
    
    1. Added the following to my Startup class:
    services.AddSwaggerGen(setupAction =>
        {
            setupAction.SwaggerDoc(
                "MyAppAPIDocumentation",
                new OpenApiInfo() { Title = "MyApp API", Version = "1" });
    
            var xmlDocumentationFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
            var xmlDocumentationFullPath = Path.Combine(AppContext.BaseDirectory, xmlDocumentationFile);
    
            setupAction.IncludeXmlComments(xmlDocumentationFullPath);
            setupAction.DocumentFilter<XmlDocumentFilter>();
        });
    
    1. Profit