Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jquery-ui/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用Swashbuckle生成yaml swagger_C#_Asp.net Web Api_Swagger_Swashbuckle - Fatal编程技术网

C# 使用Swashbuckle生成yaml swagger

C# 使用Swashbuckle生成yaml swagger,c#,asp.net-web-api,swagger,swashbuckle,C#,Asp.net Web Api,Swagger,Swashbuckle,在我的Web API项目中,我可以通过使用获取json文件 由于某些要求,我希望能够检索yaml文件。但问题是,我找不到任何钩子来实现这一点 有人知道这个问题的任何解决方法吗 一个选项是向项目中添加一个IDocumentFilter,以下是几个示例: private class YamlDocumentFilter : IDocumentFilter { public void Apply(SwaggerDocument swaggerDoc, SchemaReg

在我的Web API项目中,我可以通过使用获取
json
文件

由于某些要求,我希望能够检索
yaml
文件。但问题是,我找不到任何钩子来实现这一点


有人知道这个问题的任何解决方法吗

一个选项是向项目中添加一个IDocumentFilter,以下是几个示例:

    private class YamlDocumentFilter : IDocumentFilter
    {
        public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
        {
            string file = AppDomain.CurrentDomain.BaseDirectory + "swagger_yaml.txt";
            if (!File.Exists(file))
            {
                var serializer = new YamlSerializer();
                serializer.SerializeToFile(file, swaggerDoc);
            }
        }
    }


但这取决于您的项目,如果添加对YamlSerializer或YamlDotNet的额外引用是可以接受的。

根据@HelderSepu给出的想法,我设法让Swashback.AspNetCore与YamlDotNet一起生成以下通过验证的YAML

我知道这个解决方案并不理想,但可能是某些人遇到同样问题的起点:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using YamlDotNet.Core;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
using YamlDotNet.Serialization.TypeInspectors;

namespace SwaggerPhun
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version = "v1",
                    Title = "File Comment API",
                    Description = "A simple example ASP.NET Core Web API",
                    //TermsOfService = "None",
                    Contact = new Contact
                    {
                        Name = "Pawel",
                        Email = "pawel@example.com",
                    },
                    License = new License
                    {
                        Name = "Use under LICX",
                        Url = "https://example.com/license"
                    },
                });
                c.DocumentFilter<YamlDocumentFilter>();

                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetEntryAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });
        }

        private class YamlDocumentFilter : IDocumentFilter
        {
            public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
            {
                var builder = new SerializerBuilder();
                builder.WithNamingConvention(new HyphenatedNamingConvention());
                builder.WithTypeInspector(innerInspector => new PropertiesIgnoreTypeInspector(innerInspector));

                var serializer = builder.Build();

                using (var writer = new StringWriter())
                {
                    serializer.Serialize(writer, swaggerDoc);

                    var file = AppDomain.CurrentDomain.BaseDirectory + "swagger_yaml.txt";
                    using (var stream = new StreamWriter(file))
                    {
                        var result = writer.ToString();
                        stream.WriteLine(result.Replace("2.0", "\"2.0\"").Replace("ref:", "$ref:"));
                    }
                }
            }
        }

        private class PropertiesIgnoreTypeInspector : TypeInspectorSkeleton
        {
            private readonly ITypeInspector _typeInspector;

            public PropertiesIgnoreTypeInspector(ITypeInspector typeInspector)
            {
                this._typeInspector = typeInspector;
            }

            public override IEnumerable<IPropertyDescriptor> GetProperties(Type type, object container)
            {
                return _typeInspector.GetProperties(type, container).Where(p => p.Name != "extensions" && p.Name != "operation-id");
            }

        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.IO;
使用System.Linq;
运用系统反思;
使用Microsoft.AspNetCore.Builder;
使用Microsoft.AspNetCore.Hosting;
使用Microsoft.Extensions.Configuration;
使用Microsoft.Extensions.DependencyInjection;
使用swashback.AspNetCore.Swagger;
使用swashback.AspNetCore.SwaggerGen;
使用YamlDotNet.Core;
使用YamlDotNet.Serialization;
使用YamlDotNet.Serialization.NamingConventions;
使用YamlDotNet.Serialization.typeinspector;
名称空间虚张声势
{
公营创业
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
services.AddMvc();
services.AddSwaggerGen(c=>
{
c、 大摇大摆的文件(“v1”,新信息
{
Version=“v1”,
Title=“文件注释API”,
Description=“一个简单的ASP.NET核心Web API示例”,
//TermsOfService=“无”,
联系人=新联系人
{
Name=“Pawel”,
电子邮件=”pawel@example.com",
},
许可证=新许可证
{
Name=“在LICX下使用”,
Url=”https://example.com/license"
},
});
c、 DocumentFilter();
//为Swagger JSON和UI设置注释路径。
var xmlFile=$“{Assembly.GetEntryAssembly().GetName().Name}.xml”;
var xmlPath=Path.Combine(AppContext.BaseDirectory,xmlFile);
c、 includexmlcoments(xmlPath);
});
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
公共无效配置(IApplicationBuilder应用程序,IHostingEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
//使中间件能够将生成的Swagger作为JSON端点提供服务。
app.UseSwagger();
//允许中间件为swagger ui(HTML、JS、CSS等)提供服务,并指定swagger JSON端点。
app.UseSwaggerUI(c=>
{
c、 SwaggerEndpoint(“/swagger/v1/swagger.json”,“我的API v1”);
});
}
私有类YamlDocumentFilter:IDocumentFilter
{
公共无效应用(SwaggerDocument swaggerDoc、DocumentFilterContext上下文)
{
var builder=新的SerializerBuilder();
builder.WithNamingConvention(新的连字符NamingConvention());
builder.WithTypeInspector(innerInspector=>新属性InnerTypeInspector(innerInspector));
var serializer=builder.Build();
使用(var writer=new StringWriter())
{
serializer.Serialize(writer,swaggerDoc);
var file=AppDomain.CurrentDomain.BaseDirectory+“swagger_yaml.txt”;
使用(var-stream=newstreamwriter(文件))
{
var result=writer.ToString();
stream.WriteLine(result.Replace(“2.0”,“2.0”)。Replace(“ref:”,“$ref:”);
}
}
}
}
私有类属性ignoreTypeInspector:TypeInspectorSkleton
{
专用只读ITypeInspector _typeInspector;
公共属性IgnoreTypeInspector(ITypeInspector typeInspector)
{
这个._typeInspector=typeInspector;
}
公共重写IEnumerable GetProperties(类型,对象容器)
{
return _typeInspector.GetProperties(type,container).Where(p=>p.Name!=“extensions”&&p.Name!=“operation id”);
}
}
}
}
支持生成YAML文件。如何使用它:

app.UseSwaggerUI(x => { x.SwaggerEndpoint("/swagger/v1/swagger.yaml", "Zeipt Dashboard API"); });

这似乎是正确的做法,我一直无法证实。但这可能是因为我正在部署一个服务结构。arghhh!细节中的魔鬼(服务结构)是的,您可能需要修改该示例或尝试使用不同的依赖项…我使用YamlSerializer添加了一个示例,该示例的代码看起来简单多了,并且我验证了它在Azure上可以工作:@HelderSepu您可以提供一个更完整的示例,例如库、名称空间、,用法等@PawełG.看看这里:因为我有一点时间,我用代码制作了一个库存根,它模仿了原始的Swashbuck,但添加了一个
yaml
端点-源代码可以在中找到:我们可以用这种方法将swagger.json文件保存到本地吗?
app.UseSwaggerUI(x => { x.SwaggerEndpoint("/swagger/v1/swagger.yaml", "Zeipt Dashboard API"); });