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 关注
- 89 浏览
添加回答
举报