Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 47 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ Perfect for developers seeking both flexibility and precision in their API solut
## Example

```cs

var collection = new ServiceCollection();
using var services = collection.BuildServiceProvider();
services.AddOpenApi(opt =>
Expand All @@ -37,6 +36,53 @@ services.AddOpenApi(opt =>

## Extensions

### Enrich with XML comments
XML documentation is often used to make a comprehensive documentation to your API documentation.
By using XML comments it is easy to describe various aspects of your code, including methods, properties, parameters, return values, and more.

To create a detailed documentation using XML comments, you need to enable it in your project. Like shown below:

```xml
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.0" />
<PackageReference Include="MMonrad.OpenApi.Extensions" Version="0.0.17" />
</ItemGroup>

</Project>
```

After enabling XML Comments you will maybe see a new warning show up `CS1591`, to suppress the warning add this to your csproj file:

```xml
...
<PropertyGroup>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
...
```

Lastly add it to your Open Api configuration

```cs
var collection = new ServiceCollection();
using var services = collection.BuildServiceProvider();
services.AddOpenApi(opt =>
{
opt.OpenApiVersion = OpenApiSpecVersion.OpenApi3_0;
opt.ConfigureNodaTime();
opt.AddXmlComments<Module>();
});
```

## NodaTime
Allows to configure Asp.Net Core and OpenApi to use NodaTime types.

Expand Down
3 changes: 3 additions & 0 deletions Samples/OpenApi.Sample/Module.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
namespace OpenApi.Sample;

internal class Module;
1 change: 1 addition & 0 deletions Samples/OpenApi.Sample/OpenApi.Sample.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>

<ItemGroup>
Expand Down
8 changes: 8 additions & 0 deletions Samples/OpenApi.Sample/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using NodaTime;
using OpenApi.Extensions.Extensions;
using OpenApi.NodaTime.Extensions;
using OpenApi.Sample;
using Scalar.AspNetCore;

var builder = WebApplication.CreateBuilder(args);
Expand All @@ -18,6 +19,7 @@
{
opt.AddDescription("This project contains samples on the extensions library OpenApi.Extensions.");
opt.ConfigureNodaTime();
opt.AddXmlComments<Module>();
opt.AddResponseType<ProblemDetails>(HttpStatusCode.BadRequest);
});

Expand Down Expand Up @@ -54,7 +56,13 @@

app.Run();

/// <summary>
/// Shows the weather forecast
/// </summary>
internal record WeatherForecast(LocalDate Date, int TemperatureC, string? Summary)
{
/// <summary>
/// Uses TemperatureC to calculate TemperatureF
/// </summary>
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
29 changes: 28 additions & 1 deletion src/OpenApi.Extensions/Extensions/OpenApiOptionsExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@
using System.Collections.Generic;
using System.Net;
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.OpenApi;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using OpenApi.Extensions.Transformers;
using OpenApi.Extensions.Transformers.Documents;
using OpenApi.Extensions.Transformers.Operations;
using OpenApi.Extensions.Transformers.Schemas;

namespace OpenApi.Extensions.Extensions;

Expand Down Expand Up @@ -466,6 +468,31 @@ public static OpenApiOptions AddType<TConcrete, TType>(this OpenApiOptions optio
return options;
}

/// <summary>
/// Loads the assembly and adds XML documentation to the type.
/// </summary>
/// <typeparam name="T">The assembly type to add XML documentation for.</typeparam>
/// <returns>The updated <see cref="OpenApiOptions"/> instance.</returns>
public static OpenApiOptions AddXmlComments<T>(this OpenApiOptions options)
where T : class, new()
{
options.AddSchemaTransformer<XmlSchemaTransformer<T>>();
return options;
}

/// <summary>
/// Loads the assembly and adds XML documentation to the type.
/// </summary>
/// <typeparam name="T">The assembly type to add XML documentation for.</typeparam>
/// <returns>The updated <see cref="OpenApiOptions"/> instance.</returns>
public static OpenApiOptions AddXmlComments<T>(this OpenApiOptions options,
Func<JsonTypeInfo, JsonPropertyInfo?, string?, ValueTask<string?>> onChangeDescription)
where T : class, new()
{
options.AddSchemaTransformer(new XmlSchemaTransformer<T>(onChangeDescription));
return options;
}

private static string FormatJson<T>(T obj, JsonSerializerOptions? jsonSerializerOptions)
{
var formatToJson = JsonSerializer.Serialize(obj, jsonSerializerOptions);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
using Microsoft.AspNetCore.OpenApi;
using Microsoft.OpenApi.Models;

namespace OpenApi.Extensions.Transformers;
namespace OpenApi.Extensions.Transformers.Documents;

public class DescriptionDocumentTransform : IOpenApiDocumentTransformer
{
Expand Down
106 changes: 106 additions & 0 deletions src/OpenApi.Extensions/Transformers/Schemas/XmlSchemaTransformer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Reflection;
using System.Text.Json.Serialization.Metadata;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.XPath;
using Microsoft.AspNetCore.OpenApi;
using Microsoft.OpenApi.Models;

namespace OpenApi.Extensions.Transformers.Schemas;

public class XmlSchemaTransformer<T> : IOpenApiSchemaTransformer
where T : class, new()
{
private readonly ConcurrentDictionary<string, string?> _descriptions = [];
private readonly Func<JsonTypeInfo, JsonPropertyInfo?, string?, ValueTask<string?>>? _getDescription;
private readonly Lazy<XPathNavigator?> _navigator;

public XmlSchemaTransformer(Func<JsonTypeInfo, JsonPropertyInfo?, string?, ValueTask<string?>>? getDescription = null)
{
_getDescription = getDescription;
_navigator = new Lazy<XPathNavigator?>(CreateNavigator);
}

public async Task TransformAsync(OpenApiSchema schema, OpenApiSchemaTransformerContext context, CancellationToken cancellationToken)
{
var memberInfo = context.JsonPropertyInfo?.DeclaringType;
if (schema.Description is null &&
memberInfo is not null &&
GetMemberName(context.JsonTypeInfo, context.JsonPropertyInfo) is { Length: > 0 } memberName)
{
schema.Description = await GetDescription(memberName, context.JsonTypeInfo, context.JsonPropertyInfo);
}
}

private async ValueTask<string?> GetDescription(string memberName, JsonTypeInfo typeInfo, JsonPropertyInfo? propertyInfo)
{
if (_descriptions.TryGetValue(memberName, out var description))
{
return description;
}

var navigator = _navigator.Value;

var xpath = $"/doc/members/member[@name='{memberName}']/summary";
var summaryNode = navigator?.SelectSingleNode(xpath);
description = summaryNode?.Value.Trim();
if (_getDescription is not null)
{
description = await _getDescription(typeInfo, propertyInfo, description);
}

_descriptions[memberName] = description;

return description;
}

private static XPathNavigator? CreateNavigator()
{
var assemblyPath = typeof(T).Assembly.Location;
var xmlPath = Path.ChangeExtension(assemblyPath, ".xml");

if (!File.Exists(xmlPath))
{
return null;
}

using var reader = XmlReader.Create(xmlPath);
return new XPathDocument(reader).CreateNavigator();
}

private static string? GetMemberName(JsonTypeInfo typeInfo, JsonPropertyInfo? propertyInfo)
{
if (propertyInfo is null)
{
return $"T:{typeInfo.Type.FullName}";
}

var declaringType = propertyInfo.DeclaringType.FullName;
if (declaringType is null)
{
return null;
}

var memberName = propertyInfo.AttributeProvider switch
{
MemberInfo member => member.Name,
_ => $"{char.ToUpperInvariant(propertyInfo.Name[0])}{propertyInfo.Name[1..]}"
};

// Determine member type prefix: Property (P) or Field (F)
var memberType = propertyInfo.AttributeProvider switch
{
PropertyInfo => "P",
FieldInfo => "F",
_ => null
};

return memberType is null
? null
: $"{memberType}:{declaringType}{Type.Delimiter}{memberName}";
}
}