RicoSuter / NSwag

The Swagger/OpenAPI toolchain for .NET, ASP.NET Core and TypeScript.
http://NSwag.org
MIT License
6.78k stars 1.29k forks source link

Add custom annotations to generated classes #4433

Open florianh77 opened 1 year ago

florianh77 commented 1 year ago

Is it possible to add custom annotations when generating c# server or client classes? I would like the same models when communicating to the backend using RPC.

davidkeaveny commented 1 year ago

I'm guessing you could achieve this by providing customised Liquid templates, which add the necessary attributes in addition to, or instead of, the ones that NSwag applies by default.

Parcley commented 1 year ago

I have a very similar use-case like @florianh77: I want to add [ExcludeFromCodeCoverage] to every generated class (as this is the annotation that is understood by our code coverage tool). @davidkeaveny I find your answer interesting and I have also found some resources which point me one step further:

davidkeaveny commented 1 year ago

@Parcley it's probably easiest to use NSwagStudio, which provides a more user-friendly approach to setting up the .nswag configuration file. When configuring the CSharp Client, it's near the bottom of the configuration page, in a section labelled Templating in a field named Template Directory; it should be sufficient to use a path that is relative to your .nswag file.

If you want to edit the .nswag file by hand, then the relevant section of the configuration looks something like this:

{
  "codeGenerators": {
    "openApiToCSharpClient": {
      "templateDirectory": "Templates"
    }
  }
}