.Net Core and Swagger - How to document class in .Net Core

AdrianH

Expert Member
Joined
Feb 27, 2005
Messages
4,533
Reaction score
2,741
Location
Essex, UK
Hi All,

Busy creating an web api project with .Net Core and documenting the API with Swagger.

I am using the below package and everything works except for a want to document the ProblemDetails class with is part of .Net Core.


As this class is not mine, I am unable to annotate the class and properties due to not having the source in my project. I can create a subclass and reintroduce all the properties and annotate them, and then Swagger works fine, but this is not a solution I really like.

Is there a way create a class documentation without actually having access to the class source.

NB: I am using the Swashbuckle.AspNetCore.Annotations and not the XML comments/document to generate the Swagger docs.


Thanks
 
the "correct" way to do this is to have a DTO, instead of returning the 3rd party class in your API.

another option, similar to sub-classing, is to create an interface that has the swagger annotations, then create a partial class that implements the 3rd party class

Code:
public interface MyInterface
{
   [SwaggerSchema("The name", ReadOnly = true)]
   string Name { get; }
   [SwaggerSchema("The email", ReadOnly = true)]
   string Email { get; }
}

public partial class ThirdPartyClass: MyInterface { }

Then your API returns `MyInterface` instead of `ThirdPartyClass`
 
the "correct" way to do this is to have a DTO, instead of returning the 3rd party class in your API.

another option, similar to sub-classing, is to create an interface that has the swagger annotations, then create a partial class that implements the 3rd party class

Code:
public interface MyInterface
{
[SwaggerSchema("The name", ReadOnly = true)]
string Name { get; }
[SwaggerSchema("The email", ReadOnly = true)]
string Email { get; }
}

public partial class ThirdPartyClass: MyInterface { }

Then your API returns `MyInterface` instead of `ThirdPartyClass`

Thanks

I know I should be using DTOs but this class (and the validation) is based on the standard structures for error and invalid responses (according the the comments in said coce). Would you class these classes as 3rd party if they are actually part of the .Net Core libraries? If you decorate your controller with [ApiController], ProblemDetails and ProblemDetailsValidation are the structures returned on exceptions and model errors.

What I have done is inherit from ProblemDetails and reintroduce each property, which basically get/set to the base property, just so I can decorate the properties...feels so wrong!

Unfortunately the ProblemDetails class isn't declared at partial. Unless something has changed, both classes must be marked as partial from what I recall. I do like the interface idea, going to see what I can do.
 
Last edited:
Top
Sign up to the MyBroadband newsletter
X