Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use Swagger with AspNetCore Odata?

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.

like image 516
Svetlana Gurskaya Avatar asked Jul 25 '18 20:07

Svetlana Gurskaya


1 Answers

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!

like image 73
Svetlana Gurskaya Avatar answered Sep 19 '22 19:09

Svetlana Gurskaya