可以将Swagger与AspNetCore Odata一起使用吗?

时间:2018-07-25 20:29:29

标签: c# odata swagger core nswag

昨天,我搜索了有关如何在Core Odata上使用swagger的解决方案,我尝试了很少的库,但没有成功,它表明当前尚不完全支持它。

1 个答案:

答案 0 :(得分:4)

此信息可能对某人有用。实际上,可以使用NSwag并从框中创建Odata Core的文档。有解决方法。

只需将招摇和Odata设置添加到Startup.cs

     public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                options.SerializerSettings.ContractResolver =
                    new Newtonsoft.Json.Serialization.DefaultContractResolver();
            });

            services.AddOData();
      //etc
        }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    var builder = new ODataConventionModelBuilder(app.ApplicationServices));           
    builder.EntitySet<Test>(nameof(Test));

    app.UseMvc(routebuilder =>
    {
        routebuilder.MapODataServiceRoute("odata", "odata", builder.GetEdmModel());
    });

    app.UseSwaggerUi(typeof(Startup).GetTypeInfo().Assembly,
        settings =>
        {
            settings.GeneratorSettings.DefaultPropertyNameHandling = PropertyNameHandling.CamelCase;
        });           
    app.UseMvc();
    //etc
 }

接下来,将带有route属性的Controller标记为WebApi。注意:路由应该与odata不同。 将[EnableQuery]添加到您的IQueryable Action中。注意2:您不能将[FromODataUri]用于swagger文档,将其标记为[SwaggerIgnore]

[Produces("application/json")]
[Route("api/test")] 
public class TestController : Controller
{

    [HttpGet]
    [EnableQuery]
    public IQueryable<Test> Get()
    {
        return _testService.Query();
    }

    //etc
}

大张旗鼓地奔跑!