Integrate swashbuckle swagger with odata in ASP.Net Core

Ayushi Sharma picture Ayushi Sharma · Jun 20, 2018 · Viewed 13.1k times · Source

I have tried to implement both ( swagger and odata ) in asp.net core, but it's not working.

I'm unable to integrate the route given for odata.

I have the following Configuration and I receive a generic error.

Configuration

This is the error

this is the error

Answer

Kizmar picture Kizmar · Jul 30, 2018

We ran into the same issue when adding OData to our .Net Core project. The workarounds shown in the code snippet on this post fixed our API error(s) when Swagger UI loads.

As far as I can tell, OData isn't supported in Swashbuckle for AspNetCore. So after adding the workaround code in the link above, our Swagger UI works, but none of the OData endpoints show.

Code snippet from the link:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        services.AddOData();

        // Workaround: https://github.com/OData/WebApi/issues/1177
        services.AddMvcCore(options =>
        {
            foreach (var outputFormatter in options.OutputFormatters.OfType<ODataOutputFormatter>().Where(_ => _.SupportedMediaTypes.Count == 0))
            {
                outputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/prs.odatatestxx-odata"));
            }
            foreach (var inputFormatter in options.InputFormatters.OfType<ODataInputFormatter>().Where(_ => _.SupportedMediaTypes.Count == 0))
            {
                inputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/prs.odatatestxx-odata"));
            }
        });
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {                
        var builder = new ODataConventionModelBuilder(app.ApplicationServices);

        builder.EntitySet<Product>("Products");

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

            // Workaround: https://github.com/OData/WebApi/issues/1175
            routes.EnableDependencyInjection();
        });
    }
}