Is it possible to use Swagger with AspNetCore Odata?
Asked Answered
R

1

6

Yesterday I searched solution how to use swagger on Core Odata, I tried few libraries but with no success, it seams that currently it's not fully supported.

Rockwood answered 25/7, 2018 at 20:29 Comment(1)
Github issue: github.com/RSuter/NSwag/issues/730#issuecomment-410293504Stomatology
R
5

May be this info could be useful for somebody. Actually It's possible to use NSwag and create documentation for Odata Core from the box. There is workaround.

Just add swagger and Odata settings to 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
 }

Next mark Controller with route attribute as it would WebApi. Note: route should be different from odata. Add [EnableQuery] to your IQueryable Action. Note2: you can't use [FromODataUri] for swagger docs Action with it should be marked as [SwaggerIgnore]

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

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

    //etc
}

Get swagger run!

Rockwood answered 25/7, 2018 at 20:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.