According to the documentation for Swashbuckle, only a few XML comments are supported in the latest version. It seems like XML comments such as <example> or <see> are not currently supported but will be implemented in Swashbuckle v6.
Until then, is there a workaround I can do to mimick the behavior of <example> or <see>?
I'd like to somehow add a link (using <see> with cref) in the <summary> of an enum, which is listed under the model of an endpoint, to point to the enum's corresponding endpoint (a different endpoint in Swagger that gets the list of types of that enum).
Edit (not sure how to format in comment):
I'd like Swagger to detect <see> and display a link in the enum's description to a different endpoint
/// <summary>
/// Generic description.
/// Find enum types <see cref="ContactEntityType">here</see>
/// </summary>
[PropertyRequired, PropertyStringAsEnum(typeof(ContactEntityType))]
[DataMember(Name = "entityType")]
public NamedReference EntityType { get; set; }
In 2022 the latest version of swagger supports parameter comments.
/// <param name="MyParamaterName" example="123"> Should be defined as model MyModelName</param>
[HttpPost]
[Route("SomeWebApiFunction")]
public async Task<bool> SomeWebApiFunction(MyModelName MyParamaterName)
{
return true;
}
public class MyModelName
{
public string PropName { get; set; }
}
Swaggers pretty good at giving each section a unique id, you can check each sections id attribute with the inspect element. This makes it pretty easy to link around the document. For example we could add a link to scroll to the MyModelName description;
/// <param name="MyParamaterName" example="123"> Should be defined as model <a href='#model-MyModelName'>MyModelName</a></param>
Don't forget to IncludeXmlComments
builder.Services.AddSwaggerGen(c => {
string fileName = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml";
var filePath = Path.Combine(AppContext.BaseDirectory, fileName);
c.IncludeXmlComments(filePath);
});
If your using Visual Studio, be sure Generate XML comments are turned on.
If your using Asp.net Core and the xml is not being generated, you have to add the following line within the PropertyGroup of your .csproj file.
<PropertyGroup>
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\YourApplicationNameGoesHere.xml</DocumentationFile>
</PropertyGroup>
Replace YourApplicationNameGoesHere with the name of your application. If for some reason you do not know the xml file name, you can find it in the output folder of your project build.
You can use an ISchemaFilter or an IDocumentFilter to modify the resulting SwaggerDoc.
Here are some samples:
private class ApplySchemaVendorExtensions : ISchemaFilter
{
public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
{
// Modify the example values in the final SwaggerDocument
//
if (schema.properties != null)
{
foreach (var p in schema.properties)
{
switch (p.Value.format)
{
case "int32":
p.Value.example = 123;
break;
case "double":
p.Value.example = 9858.216;
break;
}
}
}
}
}
_
private class ApplyDocumentVendorExtensions : IDocumentFilter
{
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
{
schemaRegistry.GetOrRegister(typeof(ExtraType));
//schemaRegistry.GetOrRegister(typeof(BigClass));
var paths = new Dictionary<string, PathItem>(swaggerDoc.paths);
swaggerDoc.paths.Clear();
foreach (var path in paths)
{
if (path.Key.Contains("foo"))
swaggerDoc.paths.Add(path);
}
}
}
And to add a link just use the anchor tag :
/// <summary>Details - testing anchor: TestPost</summary>
Related
Based on the Swagger documentation I must be able to add some examples for my class fields, something like:
But I can't find any way to add these examples to my classes.
You can enable XML Comments and then use the <example> element to define an example. Here's an example of using an <example>:
public class CompanyValidationResponse
{
/// <example>1234</example>
public int CompanyId { get; set; }
/// <example>Damage, Inc</example>
public string CompanyName { get; set; }
}
To do this first you need to add XML documentation to your class. Here is an example.
namespace WebApplication44
{
/// <summary>
/// Display Weather Forecast
/// </summary>
public class WeatherForecast
{
/// <summary>
/// Date of the weather
/// </summary>
public DateTime Date { get; set; }
/// <summary>
/// Temperature in Degree Celesuis
/// </summary>
public int TemperatureC { get; set; }
/// <summary>
/// Temperature in Fahrenheit
/// </summary>
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
/// <summary>
/// Summary of the Weather. It can be "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
/// </summary>
public string? Summary { get; set; }
}
}
Next, you need to enable the Documentation File > Generate a File containing API documentation option in the Project Properties in Visual Studio - No need to change the location.
Finally, modify the swagger generation code like this.
var xmlDoc = Path.ChangeExtension(Assembly.GetExecutingAssembly().Location, "xml");
builder.Services.AddSwaggerGen(options => options.IncludeXmlComments(xmlDoc, true));
Then you will be able to see the Open API doc like this.
Add documentation of multiple projects
I wanted to add a solution for how to display examples and other documentation when the types documented do not live in your primary web/ api project but in other Domain or Model projects as is advised by applying Seperation of concerns.
I came across this issue because I usually decouple my API project holding the endpoints from the actual business logic which lives in my Domain project using MediatR but my API might return types defined in the Domain project, therefore I still would like to document the returned types.
Here what the multi-project solution looks like (conceptually):
My.Example.Project.sln
|- My.Example.Project.Api
| |- ...
| |- My.Example.Project.Api.csproj
|- My.Example.Project.Domain
| |- ...
| |- My.Example.Project.Domain.csproj
In order for this to work you need to enable the generation of XML documentation for each of the projects you wish to include the documentation off by setting this in the respective *.csproj files:
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<!-- Optional: Disable warnings for missing XML doc comments -->
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
Now document your model/ DTO objects using <example> in the My.Example.Project.Domain project.
// A DTO in the domain project
namespace My.Example.Project.Domain.DTOs
{
public class MyApiDto
{
/// <summary>
/// Unique ID.
/// </summary>
/// <example>b521fb69-d6fc-4c20-83bf-46a3f391eb52</example>
public Guid Id { get; set; }
/// <summary>
/// Name
/// </summary>
/// <example>John</example>
public string Name { get; set; }
}
}
And of course you'll document your API endpoint in the My.Example.Project.Domain project.
// A controller in the API project
namespace My.Example.Project.Api.Controllers
{
[ApiController]
[Route("api")]
public class DtoController : ControllerBase
{
private readonly IMediator _mediator;
public TextFilesController(IMediator mediator)
{
_mediator = mediator;
}
/// <summary>
/// Gets the DTO.
/// </summary>
/// <response code="200">API got the DTO</response>
[HttpGet("something/{id}", Name = nameof(GetDto))]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(GetDtoResponse))]
public async Task<ActionResult<GetDtoResponse>> GetDto(Guid id)
{
var request = new GetDtoRequest(id);
var respone = await _mediator.Send(request); // returns the DTO from the Domain project
return Ok(response);
}
}
}
Now you just need to configer Swagger Gen to look for the .xml documentation files of all of your projects instead of just the one of the executing assembly as is shown in the Microsoft Docs.
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo()
{
Version = "1.0.0",
Title = "My Project API",
});
// Include docs from current API assembly (as described in MS Docs)
var executingAssembly = Assembly.GetExecutingAssembly();
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{executingAssembly.GetName().Name}.xml"));
// Additionally include the documentation of all other "relevant" projects
var referencedProjectsXmlDocPaths = executingAssembly.GetReferencedAssemblies()
.Where(assembly => assembly.Name != null && assembly.Name.StartsWith("My.Example.Project", StringComparison.InvariantCultureIgnoreCase))
.Select(assembly => Path.Combine(AppContext.BaseDirectory, $"{assembly.Name}.xml"))
.Where(path => File.Exists(path));
foreach (var xmlDocPath in referencedProjectsXmlDocPaths)
{
options.IncludeXmlComments(xmlDocPath);
}
});
In order to determine the "relevant" assemblies you can use GetReferencedAssemblies() on the current assembly. As your API will return types of your domain project the domain assembly will be referenced in the API projects. Unfortunately tons of other assemblies which you have not created will also be returned. As there is no concept of my own assembly and each assembly is just like any other assembly the only way to filter your assemblies is using their name e.g. using StartsWith(). Then create the path the same way as you would with a single file and finally check if that documentation .xml file actually exists as you might have projects referenced in your API projects which do not generate .xml documention.
Last but not least loop over all the paths you've just created and tell Swagger Gen to include those files when generating the OpenAPI spec using options.IncludeXmlComments().
Now when you start your solution the documentation and examples should be displayed.
I have a controller method that looks like this:
[HttpPost]
[Consumes("application/x-www-form-urlencoded")]
[Produces("application/json")]
public async Task<IActionResult> GenerateTokenAsync([FromForm]TokenParameters tokenParameters)
TokenParameters looks like this:
public class TokenParameters
{
/// <summary>
/// Specifies the grant type. Must be "password".
/// </summary>
[Required]
public GrantType? grant_type
{
get;
set;
}
/// <summary>
/// Specifies the username.
/// </summary>
[Required]
public string username
{
get;
set;
}
/// <summary>
/// Specifies the password.
/// </summary>
[Required]
public string password
{
get;
set;
}
}
Everything works fine, but the Swagger UI is not picking up the /// triple slash comments for the members. My other controllers use FromBody and /// triple slash comments work fine with those. Seems like the model section at the bottom picks up the comments, but I'm talking about the model description in the light green section when I look at the controller.
I've looked in the schema registry, and the descriptions are indeed there.
EDIT: Using Swashbuckle 5.0 Beta.
EDIT #2: It also doesn't seem to pick up the example values from the schema registry for form parameters either.
Any ideas?
Make sure that your project has the Generate xml documentation option checked.
Also, when you configure Swagger, make sure to have it include the xml comments.
// Register the Swagger generator, defining one or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v2", new Info { Title = "my API", Version = "v2" });
// Set the comments path for the Swagger JSON and UI.
var basePath = PlatformServices.Default.Application.ApplicationBasePath;
var xmlPath = Path.Combine(basePath, "myapp.xml");
c.IncludeXmlComments(xmlPath);
});
I too had this issue. My issue was that I was not including the correct XML documentation files. I was including only the web application XML documentation while I had my "creation options" object that was being created from the form data defined in another assembly. Once I had this assembly producing XML documentation and including it in the swagger configuration I was able to get descriptions for each form field item.
Here is my controller method handling the POST from the client:
/// <summary>
/// Create a new very complex object.
/// </summary>
/// <param name="creationOptions">Very complex creation options</param>
/// <returns>The very complex object as a data transfer object.</returns>
[HttpPost]
[Consumes("application/x-www-form-urlencoded")]
public async Task<IActionResult> CreateVeryComplexObject([FromForm] VeryComplexObjectCreationOptions creationOptions) { }
When adding the swagger services I included the documentation from both assemblies:
services.AddSwaggerGen(config =>
{
// All my other swagger configuration here...
config.IncludeXmlComments(System.IO.Path.Combine(AppContext.BaseDirectory, "MyService.API.Web.xml"));
config.IncludeXmlComments(System.IO.Path.Combine(AppContext.BaseDirectory, "MyService.API.Contracts.xml"));
});
This is on Swashbuckle 4.0.1.
I am using Swagger as my API tooling framework and it is working out great so far. I just came across this page https://petstore.swagger.io/
and saw how each method has a description. For example,
POST: pet/ is described by add a new Pet to the store. I thought adding something like [Description("Description text")] should do it but it just does not. How can I achieve this?
This is well documented in the project:
https://github.com/domaindrivendev/Swashbuckle.AspNetCore#include-descriptions-from-xml-comments
Include Descriptions from XML Comments
To enhance the generated docs with human-friendly descriptions, you can annotate controller actions and models with Xml Comments and configure Swashbuckle to incorporate those comments into the outputted Swagger JSON:
1 - Open the Properties dialog for your project, click the "Build" tab and ensure that "XML documentation file" is checked. This will produce a file containing all XML comments at build-time.
At this point, any classes or methods that are NOT annotated with XML comments will trigger a build warning. To suppress this, enter the warning code "1591" into the "Suppress warnings" field in the properties dialog.
2 - Configure Swashbuckle to incorporate the XML comments on file into the generated Swagger JSON:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1",
new Info
{
Title = "My API - V1",
Version = "v1"
}
);
var filePath = Path.Combine(System.AppContext.BaseDirectory, "MyApi.xml");
c.IncludeXmlComments(filePath);
}
3 - Annotate your actions with summary, remarks and response tags:
/// <summary>
/// Retrieves a specific product by unique id
/// </summary>
/// <remarks>Awesomeness!</remarks>
/// <response code="200">Product created</response>
/// <response code="400">Product has missing/invalid values</response>
/// <response code="500">Oops! Can't create your product right now</response>
[HttpGet("{id}")]
[ProducesResponseType(typeof(Product), 200)]
[ProducesResponseType(typeof(IDictionary<string, string>), 400)]
[ProducesResponseType(500)]
public Product GetById(int id)
4 - You can also annotate types with summary and example tags:
public class Product
{
/// <summary>
/// The name of the product
/// </summary>
/// <example>Men's basketball shoes</example>
public string Name { get; set; }
/// <summary>
/// Quantity left in stock
/// </summary>
/// <example>10</example>
public int AvailableStock { get; set; }
}
5 - Rebuild your project to update the XML Comments file and navigate to the Swagger JSON endpoint. Note how the descriptions are mapped onto corresponding Swagger fields.
NOTE: You can also provide Swagger Schema descriptions by annotating your API models and their properties with summary tags. If you have multiple XML comments files (e.g. separate libraries for controllers and models), you can invoke the IncludeXmlComments method multiple times and they will all be merged into the outputted Swagger JSON.
Following the instructions carefully you should get something that looks like:
https://swashbucklenetcore.azurewebsites.net/swagger/
For ASP.Net Core projects:
install nuget package Swashbuckle.AspNetCore.Annotations
Use SwaggerOperation attribute for a methods like [SwaggerOperation(Summary = "Write your summary here")]
Enable annotations in Startup method ConfigureServices like the following:
services.AddSwaggerGen(c =>
{
c.EnableAnnotations();
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});
To exclude public method from appearing in swagger ui use attribute [ApiExplorerSettings(IgnoreApi = true)]. It is useful cause these methods can break swagger for some reason.
Launch project, go to localhost:[port number]/swagger and enjoy.
We use additional attributes to add required detail to the swagger documentation:
[SwaggerOperationSummary("Add a new Pet to the store")]
[SwaggerImplementationNotes("Adds a new pet using the properties supplied, returns a GUID reference for the pet created.")]
[Route("pets")]
[HttpPost]
public async Task<IHttpActionResult> Post()
{
...
}
And then in you swagger config make sure to apply these filters:
config.EnableSwagger("swagger",
c =>
{
c.OperationFilter<ApplySwaggerImplementationNotesFilterAttributes>();
c.OperationFilter<ApplySwaggerOperationSummaryFilterAttributes>();
The code for the filters:
public class ApplySwaggerImplementationNotesFilterAttributes : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
var attr = apiDescription.GetControllerAndActionAttributes<SwaggerImplementationNotesAttribute>().FirstOrDefault();
if (attr != null)
{
operation.description = attr.ImplementationNotes;
}
}
}
public class ApplySwaggerOperationSummaryFilterAttributes : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
var attr = apiDescription.GetControllerAndActionAttributes<SwaggerOperationSummaryAttribute>().FirstOrDefault();
if (attr != null)
{
operation.summary = attr.OperationSummary;
}
}
}
For those who look for ability to expose custom localized controller names and action descriptions without shipping XML documents to customer and inventing yet another bunch of attrubutes:
public static class SwaggerMiddlewareExtensions
{
private static readonly string[] DefaultSwaggerTags = new[]
{
Resources.SwaggerMiddlewareExtensions_DefaultSwaggerTag
};
public static void ConfigureSwagger(this IServiceCollection services)
{
services
.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
{
Title = "My API",
Version = "v 1.0"
});
// your custom config
// this will group actions by localized name set in controller's DisplayAttribute
options.TagActionsBy(GetSwaggerTags);
// this will add localized description to actions set in action's DisplayAttribute
options.OperationFilter<DisplayOperationFilter>();
});
}
private static string[] GetSwaggerTags(ApiDescription description)
{
var actionDescriptor = description.ActionDescriptor as ControllerActionDescriptor;
if (actionDescriptor == null)
{
return DefaultSwaggerTags;
}
var displayAttributes = actionDescriptor.ControllerTypeInfo.GetCustomAttributes(typeof(DisplayAttribute), false);
if (displayAttributes == null || displayAttributes.Length == 0)
{
return new[]
{
actionDescriptor.ControllerName
};
}
var displayAttribute = (DisplayAttribute)displayAttributes[0];
return new[]
{
displayAttribute.GetName()
};
}
}
where DisplayOperationFilter is:
internal class DisplayOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var actionDescriptor = context.ApiDescription.ActionDescriptor as ControllerActionDescriptor;
if (actionDescriptor == null)
{
return;
}
var displayAttributes = actionDescriptor.MethodInfo.GetCustomAttributes(typeof(DisplayAttribute), false);
if (displayAttributes == null || displayAttributes.Length == 0)
{
return;
}
var displayAttribute = (DisplayAttribute)displayAttributes[0];
operation.Description = displayAttribute.GetDescription();
}
}
Applicable for Swashbuckle 5.
A workaround is to add this to your .csproj file:
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DocumentationFile>bin\Debug\netcoreapp1.1\FileXMLName.xml</DocumentationFile>
</PropertyGroup>
You can use comment for documentation (3 slashes instead of standard 2) like:
/// <summary>
/// This is method summary I want displayed
/// </summary>
/// <param name="guid">guid as parameter</param>
/// <param name="page_number">Page number - defaults to 0</param>
/// <returns>List of objects returned</returns>
You can add a comment on the methods like the example below but what about adding comments to the request and response model?
/// <summary>
/// my summary
/// </summary>
/// <remarks>
/// remark goes here.
/// </remarks>
/// <param name="somepara">Required parameter: Example: </param>
/// <return>Returns comment</return>
/// <response code="200">Ok</response>
Yes just like Dimitar said, you can add comments to the responses with SwaggerResponse, the request is a bit different, just like you added xml comments to your action you should add to the parameters, here is an example:
using Swagger.Net.Annotations;
using System;
using System.Collections.Generic;
using System.Net;
using System.Web.Http;
using System.Web.Http.Results;
namespace Swagger_Test.Controllers
{
public class IHttpActionResultController : ApiController
{
[SwaggerResponse(HttpStatusCode.OK, "List of customers", typeof(IEnumerable<int>))]
[SwaggerResponse(HttpStatusCode.NotFound, Type = typeof(NotFoundResult))]
public IHttpActionResult Post(MyData data)
{
throw new NotImplementedException();
}
}
/// <summary>My super duper data</summary>
public class MyData
{
/// <summary>The unique identifier</summary>
public int id { get; set; }
/// <summary>Everyone needs a name</summary>
public string name { get; set; }
}
}
And in swagger that will look like:
I'm using .net core 3.0, so in addition to #Helder's response, I had to do below two more steps to make XML comments visible.
manually edit the project file.
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
add below to startup.cs service configuration method.
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "My Good API",
Version = "v1",
Description = "Doesn't hurt to add some description."
});
// Set the comments path for the Swagger JSON and UI.
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
});
From the microsoft docs for Swagger
XML comments can be enabled with the following approaches:
Manually add the highlighted lines to the .csproj file:
Enabling XML comments provides debug information for undocumented
public types and members. Undocumented types and members are indicated
by the warning message. For example, the following message indicates a
violation of warning code 1591:
I am not sure if that's what exactly you're talking about, but you can add comments to the different responses like this
[SwaggerResponse(HttpStatusCode.Unauthorized, "Authorization has been denied for this request")]
This is attribute which you use to decorate your controller method.
For those that aren't having luck with the existing answers, make sure that the project your property class lives in has the xml documentation enabled as well.
In my case, I had a separate project for my DTOs and needed to add it in there as well. Be sure to include xml comments from that project as well with another IncludeXmlComments method.
Within my API I'm trying to document the different field descriptions, however none of attributes seem to work. I know this functionality is supposed to have been recently implemented within WebAPI 5.1 (running WebAPI.HelpPage 5.1.2).
ASP.Net Web API Help Pages: Document Model Data Annotations - Work Item 877
I'm trying to document both my response model:
And the individual fields/properties
I've tried a mixture of XML comments, DataMember and Display attributes but none seem to be picked up.
/// <summary>
/// blah blah blah
/// </summary>
[DataContract(Name = "Application")]
public class Application
{
/// <summary>
/// Please Display!
/// </summary>
[DataMember(Order = 0)]
[Display(Description="Please Display!")]
[StringLength(11, MinimumLength = 11)]
public string ApplicationId { get; set; }
Here is a sample from my Areas/HelpPage/App_Start/HelpPageConfig.cs
namespace WebAPI.Areas.HelpPage
{
#pragma warning disable 1591
/// <summary>
/// Use this class to customize the Help Page.
/// For example you can set a custom <see cref="System.Web.Http.Description.IDocumentationProvider"/> to supply the documentation
/// or you can provide the samples for the requests/responses.
/// </summary>
public static class HelpPageConfig
{
public static void Register(HttpConfiguration config)
{
// remove unwanted formatters
config.Formatters.Clear();
var jsonsettings = new JsonSerializerSettings() { DateParseHandling = DateParseHandling.None };
config.Formatters.Add(new JsonMediaTypeFormatter());
config.Formatters.Add(new XmlMediaTypeFormatter());
config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/bin/WebAPI.XML")));
// create sample objects
config.SetSampleObjects(new Dictionary<Type, object>
{
{ typeof(MyResponse), new MyResponse() {
Message = "Key d795677d-6477-494f-80c5-874b318cc020 is not recognised",
Code = ResponseCode.InvalidKey, Id = null }
}
});
//*** More Sample Requests ***
}
}
#pragma warning restore 1591
}
Update 10/06/2014: My class definitions are stored in a separate library. I've noticed a discrepancy here. The main API and class definition library were generating separate XML files.
API Project
Definition Project
I've attempted to rectify this by making the Definition write to the same XML project. However this doesn't work, and the class definition entries aren't added.
To have a content displayed in Description section you need to feel section of XML comments. If you would have your model class placed inside your webapi project - then this would be a solution. Your problem is that you need to read xml documentation form 2 xml files and one time and XmlDocumentationProvider does not support that. My suggestion is to create your own MultipleFilesXmlDocumentationProvider with a little effort like this:
public class MultipleFilesXmlDocumentationProvider : IDocumentationProvider
{
IEnumerable<XmlDocumentationProvider> xmlDocumentationProviders;
public MultipleFilesXmlDocumentationProvider(IEnumerable<string> documentPaths)
{
xmlDocumentationProviders = documentPaths.Select(path => new XmlDocumentationProvider(path));
}
public string GetDocumentation(HttpParameterDescriptor parameterDescriptor)
{
foreach(XmlDocumentationProvider provider in xmlDocumentationProviders)
{
string documentation = provider.GetDocumentation(parameterDescriptor);
if(documentation != null)
return documentation;
}
return null;
}
public string GetDocumentation(HttpActionDescriptor actionDescriptor)
{
foreach (XmlDocumentationProvider provider in xmlDocumentationProviders)
{
string documentation = provider.GetDocumentation(actionDescriptor);
if (documentation != null)
return documentation;
}
return null;
}
public string GetDocumentation(HttpControllerDescriptor controllerDescriptor)
{
foreach (XmlDocumentationProvider provider in xmlDocumentationProviders)
{
string documentation = provider.GetDocumentation(controllerDescriptor);
if (documentation != null)
return documentation;
}
return null;
}
public string GetResponseDocumentation(HttpActionDescriptor actionDescriptor)
{
foreach (XmlDocumentationProvider provider in xmlDocumentationProviders)
{
string documentation = provider.GetDocumentation(actionDescriptor);
if (documentation != null)
return documentation;
}
return null;
}
}
This will be just wrapper over XmlDocumentationProvider - it will work with a collection of XmlDocumentationProvider and looks for the first one that will provide desired documentation. Then you change your configuration in HelpPageConfig to use your MultipleFilesXmlDocumentationProvider:
config.SetDocumentationProvider(
new MultipleFilesXmlDocumentationProvider(
new string[] {
HttpContext.Current.Server.MapPath("~/bin/WebAPI.XML"),
HttpContext.Current.Server.MapPath("~/bin/EntityModel.Definitions.XML")
}
)
);
Of course take into account that for the configuration above both XML files should be within WebAPI project bin folder.