Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How enable swagger for Asp.net core OData api

I have an asp.net core odata api. I want to enable swagger for this api. The version of asp.net core is 2.2 and the dependencies of this project are as below picture:

enter image description here

and the config of startup is as below:

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().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        services.AddDbContext<SeeMiddleContext>(options =>
        {
            options.UseSqlServer(
                "Data Source = 192.168.1.1;Initial Catalog=Seem;persist security info=True;user id=Sas;password=Sas1");
        });
        services.AddOData();

        services.AddSwaggerGen(options =>
        {
            options.DescribeAllEnumsAsStrings();
            options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info { Title = "eShopOnContainers - Catalog HTTP API", Version = "v1", Description = "The Catalog Microservice HTTP API. This is a DataDriven/CRUD microservice sample", TermsOfService = "Terms Of Service" });
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseMvc(routeBuilder => {

            routeBuilder.EnableDependencyInjection();

            routeBuilder.Expand().Select().OrderBy().Filter().MaxTop(40);
        });
        app.UseSwagger();

        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        });
    }
}

When I run the api and when I type "/swagger" in the url, then I will encounter the error that is shown in below picture:

enter image description here

like image 720
Mostafa Avatar asked Jul 27 '19 22:07

Mostafa


People also ask

How do I enable swagger in .NET core?

Add and configure Swagger middleware Launch the app and navigate to https://localhost:<port>/swagger/v1/swagger.json . The generated document describing the endpoints appears as shown in OpenAPI specification (openapi. json). The Swagger UI can be found at https://localhost:<port>/swagger .

How to integrate Swagger UI with ASP NET Core web API?

The Swashbuckle package has an embedded version of Swagger UI, so that it can be hosted in our ASP.NET Core app using a middleware. Each public action method in the controllers is available in the Swagger UI. We can use the Swashbuckle package to integrate Swagger into our .NET Core Web API project.

How to build web APIs with OData support using ASP NET Core?

Sample: Build web APIs with OData support using ASP.NET Core 1 Register OData. Add the Microsoft.AspNetCore.OData NuGet package to the project. ... 2 Configure middleware. OData can perform sorting, filtering, querying related data, and more. ... 3 Update the controller. ... 4 Query resources using OData. ...

What are the best open source Swagger projects?

NSwag is another open source project for generating Swagger documents and integrating Swagger UI or ReDoc into ASP.NET Core web APIs. Additionally, NSwag offers approaches to generate C# and TypeScript client code for your API.

What is Swagger (OpenAPI)?

Swagger (OpenAPI) is a language-agnostic specification for describing REST APIs. It allows both computers and humans to understand the capabilities of a REST API without direct access to the source code. Its main goals are to: Minimize the amount of work needed to connect decoupled services.


1 Answers

Try to add the following code in your ConfigureServices method

 using Microsoft.AspNet.OData.Formatter;
 using Microsoft.Net.Http.Headers;

 public void ConfigureServices(IServiceCollection services)
 {
        // 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"));
            }
        });
  }

For more details , you could refer to https://stackoverflow.com/a/51599466/10201850

like image 192
Xueli Chen Avatar answered Oct 19 '22 08:10

Xueli Chen