Fra*_*hop 11 asp.net asp.net-web-api asp.net-core
我有(超过)两个 Api POST 端点。每个都需要一个 json 作为参数。但是当我在两个端点参数类中使用相同的类名 Payload时,Swagger 不起作用。当我更改其中之一时,例如从Payload更改为Payload1 时,它会起作用。当然,我将正确的命名空间设置到包装类中,以便它找到 Payload。但我希望每次都使用相同的名称“Payload”。如何使用相同的类名Payload? 我可以在两种情况下都保留 json 名称“Payload”,只需为属性设置不同的名称(“Payload1”、“Payload2”)。有用。但是也有相同的属性名称会很好。,
端点 A
[HttpPost()]
公共异步任务 PostPerson([FromBody]JsonWrapperA jsonWrapperA)
namespace myProject.A
{
public class JsonWrapperA
{
[JsonProperty("name", Required = Required.AllowNull)]
public string Name { get; set; }
[JsonProperty("payload", Required = Required.AllowNull)]
public Payload Payload { get; set; }
}
public class Payload
{
[JsonProperty("value", Required = Required.AllowNull)]
public double Value { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
端点 B
[HttpPost()]
公共异步任务 PostCompagn([FromBody]JsonWrapperB jsonWrapperB)
namespace myProject.B
{
public class JsonWrapperB
{
[JsonProperty("compagny", Required = Required.AllowNull)]
public string Compagny { get; set; }
[JsonProperty("payload", Required = Required.AllowNull)]
public Payload Payload { get; set; }
}
public class Payload
{
[JsonProperty("age", Required = Required.AllowNull)]
public double Age{ get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
Jus*_*ude 28
默认情况下,swagger 将尝试为 API 端点的返回类型或参数类型的对象构建其架构 ID,并将在文档的“模型”部分显示这些对象。它将根据对象的类名构建这些模式 ID。
当您尝试将两个或多个类命名为相同时,即使它们位于不同的命名空间中,您也会收到冲突的 schemaIds 错误:
InvalidOperationException: Conflicting schemaIds: 为 NamespaceOne.MyClass 和 NamespaceTwo.MyClass 类型检测到相同的 schemaId。有关解决方法,请参阅配置设置 - “CustomSchemaIds”
这意味着需要配置 Swagger 以更改其生成 SchemaId 的方式。您可以简单地告诉 swagger 使用对象完全限定名称,该名称将在 schemaIds 中包含名称空间。您可以在您的Startup.cs文件中使用如下ConfigureServices方法执行此操作:
//add using statement for Swagger in Startup.cs
using Swashbuckle.AspNetCore.Swagger;
...
public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(config =>
{
//some swagger configuration code.
//use fully qualified object names
config.CustomSchemaIds(x => x.FullName);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 11
使用 Swashbuckle.AspNetCore 版本 5.5.1 我遇到了同样的问题,所以我使用 JustSomeDude 答案解决了它,但之后所有实体都显示了全名,所以我需要一种仅显示名称的方法。这就是我所做的:
options.CustomSchemaIds(x => x.FullName); // Enables to support different classes with the same name using the full name with namespace
options.SchemaFilter<NamespaceSchemaFilter>(); // Makes the namespaces hidden for the schemas
Run Code Online (Sandbox Code Playgroud)
使用这个过滤器类:
public class NamespaceSchemaFilter : ISchemaFilter
{
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
if (schema is null)
{
throw new System.ArgumentNullException(nameof(schema));
}
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
schema.Title = context.Type.Name; // To replace the full name with namespace with the class name only
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7941 次 |
| 最近记录: |