亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 C# .NET CORE 在 NSwag 文檔中添加自定義標頭?

如何使用 C# .NET CORE 在 NSwag 文檔中添加自定義標頭?

C#
MM們 2022-12-24 14:20:08
我需要添加自定義標頭,但無法弄清楚。我正在嘗試使用新的 services.AddOpenApiDocument() 而不是 services.AddSwaggerDocument()。我想在我的整個 API 上添加這些自定義標頭,而不僅僅是單個方法或控制器。我試圖添加一個運算處理器,但是當我加載 swagger UI 時,我收到以下錯誤“?? 無法呈現此組件,請查看控制臺?!边@是我的片段ConfigureServices():    services.AddOpenApiDocument(document =>    {        ...        // this works fine        document.OperationProcessors.Add(new OperationSecurityScopeProcessor("Bearer"));        document.DocumentProcessors.Add(new SecurityDefinitionAppender("Bearer", new SwaggerSecurityScheme            {                Type = SwaggerSecuritySchemeType.ApiKey,                Name = "Authorization",                In = SwaggerSecurityApiKeyLocation.Header            })        );        // this is the header i want to show up for all endpoints that is breaking        document.OperationProcessors.Add(new SampleHeaderOperationProcessor());    });這是我的操作處理器:public class SampleHeaderOperationProcessor : IOperationProcessor{    public Task<bool> ProcessAsync(OperationProcessorContext context)    {        context.OperationDescription.Operation.Parameters.Add(            new SwaggerParameter {                Name = "Sample",                Kind = SwaggerParameterKind.Header,                Type = NJsonSchema.JsonObjectType.String,                IsRequired = false,                Description = "This is a test header",                Default = "{{\"field1\": \"value1\", \"field2\": \"value2\"}}"            });        return Task.FromResult(true);    }}我在 Configure() 中唯一與此有關的東西:    app.UseSwagger();    app.UseSwaggerUi3();                              這是我的錯誤和控制臺日志: 我的錯誤和控制臺日志如果它有幫助,我正在使用ASP .NET CORE 2.2和NSwag.AspNetCore v12.1.0
查看完整描述

3 回答

?
海綿寶寶撒

TA貢獻1809條經驗 獲得超8個贊

這是我在項目中實現的示例。對我來說,它工作正常:

http://img1.sycdn.imooc.com//63a69a330001586b13260633.jpg

接口“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"

            };


        };

    });            

}


查看完整回答
反對 回復 2022-12-24
?
波斯汪

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"

    });


查看完整回答
反對 回復 2022-12-24
?
小唯快跑啊

TA貢獻1863條經驗 獲得超2個贊

這最終對我有用。直接來自 Rico Suter 的解決方案,

嘗試

Schema = new JsonSchema4 { Type = NJsonSchema.JsonObjectType.String }

代替

Type = NJsonSchema.JsonObjectType.String

(我認為 Type 在 OpenAPI 3 中已被棄用)


查看完整回答
反對 回復 2022-12-24
  • 3 回答
  • 0 關注
  • 130 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號