模型名称中的NSwag名称空间

时间:2017-07-21 15:15:15

标签: nswag

可以生成客户端代码,以便模型的类名称具有完整的名称空间作为前缀?

这应该避免相同的类名冲突。

实施例

 
com.foo.MyClass 

it.foo.MyClass

到目前为止,我得到的是MyClassMyClass2并没有多大意义。

如果名称发生碰撞,ComFooMyClassItFooMyClass应该更好。

4 个答案:

答案 0 :(得分:2)

我找到了一个使用自定义SchemaNameGenerator而不是自定义TypeNameGenerator的解决方案(我没有包信息)。

internal class MySchemaNameGenerator : DefaultSchemaNameGenerator, ISchemaNameGenerator
{
    public override string Generate(Type type)
    {
        string retValue = base.Generate(type);
        // Quite ugly but do fix the concept
        if (retValue.Equals("BaseClass"))
        {
            retValue = type.FullName.Replace(".","_");
        }
        return retValue;
    }
}

始终通过设置进行设置:

 app.UseSwaggerUi(typeof(WebApiApplication).Assembly, new SwaggerUiSettings
                {
                    SchemaNameGenerator = new MySchemaNameGenerator(),
                    ...

这样我得到了更有意义的东西

"/api/test/models/base": {
      "get": {
        "tags": [
          "Test"
        ],
        "operationId": "Test_Get2",
        "parameters": [],
        "responses": {
          "200": {
            "description": "",
            "schema": {
              "$ref": "#/definitions/WebApi_Models_BaseClass"
            },
            "x-nullable": true
          }
        }
      }
    },
    "/api/test/models/extended": {
      "get": {
        "tags": [
          "Test"
        ],
        "operationId": "Test_Get3",
        "parameters": [],
        "responses": {
          "200": {
            "description": "",
            "schema": {
              "$ref": "#/definitions/ExtendedClass"
            },
            "x-nullable": true
          }
        }
      }
    },
    "/api/test/modelli/base": {
      "get": {
        "tags": [
          "Test"
        ],
        "operationId": "Test_Get4",
        "parameters": [],
        "responses": {
          "200": {
            "description": "",
            "schema": {
              "$ref": "#/definitions/WebApi_Modelli_BaseClass"
            },
            "x-nullable": true
          }
        }
      }
    },

即使polimorphism的鉴别器属性需要基本名称“BaseClass”。

答案 1 :(得分:0)

通过C#使用NSwag时,您可以提供自己的TypeNameGenerator(通过设置对象)来自定义类名的生成方式。

答案 2 :(得分:0)

让我为最新版本的NSwag更新shadowsheep的答案:

services.AddSwaggerDocument(cfg => { cfg.SchemaNameGenerator = new CustomSchemaNameGenerator(); });

使用:

internal class CustomSchemaNameGenerator : ISchemaNameGenerator
{
    public string Generate(Type type)
    {
        return type.FullName.Replace(".", "_");
    }
}

答案 3 :(得分:0)

生成完整的命名空间。您需要设置 API 以返回具有完整命名空间的 swagger

services.AddSwaggerGen(c =>
{
    ...  //any lines you aready have 
    c.CustomSchemaIds((type) => type.FullName); //show full namespace
}

您无法通过 NSwagStudio 生成客户端,您需要使用此解决方案通过代码来生成 https://stackoverflow.com/a/45311657/1818723

这里是通过自己的代码生成客户端的现成代码

using NJsonSchema;
using NSwag;
using NSwag.CodeGeneration.CSharp;
using NSwag.CodeGeneration.OperationNameGenerators;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading.Tasks;

...

public async Task<string> GetClientCode(string swaggerUrl, CSharpClientGeneratorSettings settings)
{
    settings.OperationNameGenerator = new SingleClientFromOperationIdOperationNameGenerator();
    settings.CSharpGeneratorSettings.TypeNameGenerator = new MyTypeNameGenerator();
    var swagger = await GetAsync(swaggerUrl);
    var document = await OpenApiDocument.FromJsonAsync(swagger);
    var codeGen = new CSharpClientGenerator(document, settings);

    var code = codeGen.GenerateFile();
    return code;
}

public class MyTypeNameGenerator : ITypeNameGenerator
{
    public string Generate(JsonSchema schema, string typeNameHint, IEnumerable<string> reservedTypeNames)
    {
        if (typeNameHint == null && schema.IsEnumeration && schema.Title != null)
                return schema.Title; //for method argument when expected type is IEnumerable<Enum> (swagger definition must contain title - see last link) 

        return typeNameHint;   //this contains full namespace (assuming returned in swagger definition)
    }
}

private async Task<string> GetAsync(string uri)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

    using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
    using (Stream stream = response.GetResponseStream())
    using (StreamReader reader = new StreamReader(stream))
    {
        return await reader.ReadToEndAsync();
    }
}

这里是关于枚举标题

https://github.com/RicoSuter/NSwag/issues/2103#issuecomment-853965927