3 回答

TA貢獻1809條經驗 獲得超8個贊
這是我在項目中實現的示例。對我來說,它工作正常:
接口“IOperationProcessor”的實現:
using NSwag;
using NSwag.SwaggerGeneration.Processors;
using NSwag.SwaggerGeneration.Processors.Contexts;
using System.Threading.Tasks;
namespace api.mstiDFE._Helpers.Swagger
{
public class AddRequiredHeaderParameter : IOperationProcessor
{
public Task<bool> ProcessAsync(OperationProcessorContext context)
{
context.OperationDescription.Operation.Parameters.Add(
new SwaggerParameter
{
Name = "token",
Kind = SwaggerParameterKind.Header,
Type = NJsonSchema.JsonObjectType.String,
IsRequired = false,
Description = "Chave de acesso à API, fornecida pela RevendaCliente",
Default = "Default Value"
});
return Task.FromResult(true);
}
}
}
startup.cs 中的引用:
internal static void ConfigureServices(IServiceCollection services, IConfiguration configuration)
{
// Register the Swagger services
services.AddSwaggerDocument(config =>
{
// Adds the "token" parameter in the request header, to authorize access to the APIs
config.OperationProcessors.Add(new AddRequiredHeaderParameter());
config.PostProcess = document =>
{
document.Info.Version = "v1";
document.Info.Title = "Title ";
document.Info.Description = "API para gera??o de Documentos Fiscais Eletr?nicos (DF-e) do projeto SPED";
document.Info.TermsOfService = "None";
document.Info.Contact = new NSwag.SwaggerContact
{
Name = "Name",
Email = "Email ",
Url = "Url "
};
document.Info.License = new NSwag.SwaggerLicense
{
Name = "Use under LICX",
Url = "https://example.com/license"
};
};
});
}

TA貢獻1811條經驗 獲得超4個贊
非常感謝該線程上的原始答案。
由于 NSwag 更新,我不得不對上述答案進行一些小更新。
以下適用于我的版本(NSwag.Core:13.1.2,NJsonSchema:10.0.24):
context.OperationDescription.Operation.Parameters.Add(
new OpenApiParameter
{
Name = "HEADER_NAME",
Kind = OpenApiParameterKind.Header,
Schema = new JsonSchema { Type = JsonObjectType.String },
IsRequired = true,
Description = "Description",
Default = "Default Value"
});

TA貢獻1863條經驗 獲得超2個贊
這最終對我有用。直接來自 Rico Suter 的解決方案,
嘗試
Schema = new JsonSchema4 { Type = NJsonSchema.JsonObjectType.String }代替
Type = NJsonSchema.JsonObjectType.String(我認為 Type 在 OpenAPI 3 中已被棄用)
- 3 回答
- 0 關注
- 130 瀏覽
添加回答
舉報