How to add more details to a dotnet core api endpoint using XML Comments

  • Language:: CSharp

  • Type:: Back-end

  • Context:: This is a way to add documentation to the api endpoints so it is more clear the purpose of the specific endpoint using the comments

  • Snippet

/// <summary> 
/// Creates a TodoItem. 
/// </summary> 
/// <param name="item"></param> 
/// <returns>A newly created TodoItem</returns>
/// <remarks> 
/// Sample request: 
/// 
/// POST /Todo 
/// { 
/// "id": 1, 
/// "name": "Item #1", 
/// "isComplete": true 
/// } 
/// 
/// </remarks>
/// <response code="201">Returns the newly created item</response> 
/// <response code="400">If the item is null</response> 
[HttpPost] 
[ProducesResponseType(StatusCodes.Status201Created)] 
[ProducesResponseType(StatusCodes.Status400BadRequest)] 
public async Task<IActionResult> Create(TodoItem item) { 
	_context.TodoItems.Add(item); 
	await _context.SaveChangesAsync(); 
	return CreatedAtAction(nameof(Get), new { id = item.Id }, item); 
}

Then in the startup, add the xmlFilename and IncludeXMLComments lines:

services.AddSwaggerGen(options =>
{
	options.SwaggerDoc("v1", new OpenApiInfo { Title = "Open API", Version = "v1" });
 
+   string xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
+   options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});

📇Additional Metadata