Swagger API in asp.net core

 


 swagger editor

 create a swagger example Asp.net core web application.

Microsoft Visual Studio 2019


Give a meaningful name to the application, here I have given the name as Swagger example Application.



Once the project is created let's add a new controller. I have added HomeController. Once the Controller is created add the following NuGet packages into the application,

Swashbuckle.AspNetCore
Swashbuckle.AspNetCore.Swagger
Swashbuckle.AspNetCore.SwaggerUI




Create new folder Model and add Employee class.

public class Employee { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string EmailId { get; set; } }

[HttpGet("api/home")] public ActionResult<IEnumerable<Employee>> GetEmployees() { var employees = new List<Employee>() { new Employee() { Id = 1, FirstName = "Raj", LastName = "K", EmailId = "rajk333@gmail.com" }, new Employee() { Id = 2, FirstName = "ram", LastName = "Kumar", EmailId = "ramkumar@gmail.com" } }; return Ok(employees); // Return a 200 OK response with the list of employees }


Configuring the Swagger Middleware

Now it's time to configure services inside a startup.cs class. Open startup.cs class and add the below line of code into configuring services method.


given below :

public void ConfigureServices(IServiceCollection services) {

    // Register the Swagger or more Swagger documents

    services.AddSwaggerGen(c => {

        c.SwaggerDoc("v1", new OpenApiInfo {

            Title = "SwaggerDemoApplication", Version = "v1"

        });

    });

    services.AddControllers();

}


Add the below line of code inside configure method. Basically we are going to enable middleware for swagger UI.


public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {

        // Enable middleware Swagger for JSON endpoint.

        app.UseSwagger();

        app.UseSwaggerUI(c => {

                c.SwaggerEndpoint("/swagger/v1/swagger.json", SwaggerDemoApplication V1 ");

                });

        }


Now it's time to check the result. Run the application and navigate to https://localhost:44338/swagger/Index.html.


Now click on Get action method, after that click on execute button and see the result.



DOT NET ADDA

interested in solving the problems based on technologies like Amazon AWS ,Google Cloud, Azure and Dot related technology like asp.net, C#, asp.net core API, swagger, react js,Jquery ,javascripts, bootstrap, css,html, ms sql,IIS,WPF ,WCF,Firebase,RDLC Report etc..

إرسال تعليق (0)
أحدث أقدم