Swagger/Swashbuckle annotations in a class library

Viewed 612

I am using Swagger data annotations (x.EnableAnnotations();) and everything is working as intended in the AspNetCore app's controllers. I am able to use annotations like SwaggerOperation and SwaggerResponse to document my controllers.

Now I want to annotate my classes. Something like

public class Record : Base
{    
    [SwaggerSchema(WriteOnly = true)]
    public string AppId { get; set; }
}

My classes are in a different project from the AspNetCore app. They are DTOs and they are in their own class library. The issue is when I try install Swashbuckle.AspNetCore.Annotations in the class library I get an error in my Blazor client app that references my DTO class library.

I think the actual issue is that Swashbuckle.AspNetCore.Annotations cannot be referenced into a class library project, so doesn't work there, yet pops up on the Blazor app side.

That said I can't imagine I am the only one who has DTOs outside their main AspNetCore app.

What am I missing? Is there some other way to annotate classes in Swagger that should be used in a situation like this?

1 Answers

Based on our conversation in the comments, it seems you need to try one or more of the following

  • ensure models only used by the Blazor app are defined in class library 1, and referenced only by the Blazor project. These models can't have annotations because of the restriction that Blazor/wasm can't use Swagger's annotations library.
  • ensure models only used by the web API are defined in class library 2, and referenced by the web API project. These can have annotations.
  • for models without annotations used by by both, you can put those in class library 3 and reference that from library 1 and 2

The final case is models used by both that also have annotations. This is going to require special treatment. You can either

  • duplicate the models into class library 1 and 2, but in 2 add the annotations. This obviously destroys reuse.

or

  • define an interface for the shared models in class library 1. Implement the interface in class library 1 without annotations. Implement the interface in class library 2 (which will now have to reference 1), but add the annotations only to the implementation in class library 2.

The latter is still not ideal because there's some non-reuse. I think you'll just have to accept that.

You end up with a structure like

  1. Blazor App --> library 1 (has non-annotated shared models, non-shared/non-annotated models, interfaces for shared/annotated models) --> library 3
  2. Web API --> library 2 --> library 3 where library 2 has non-annotated models and implementations with annotations of shared interfaces)
Related