Wednesday 29 May 2019

how to add swagger in aspnetcore

follow the steps

type in searchbox : swashbuckle.aspnetcore
add this dll

now go to startup.cs file and add the code in ConfigureServices methosd

 public void ConfigureServices(IServiceCollection services)
        {
         
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "Employees Api", Version = "v1" });
            }
                );
           
        }

then in last inside the configure method write line of code
app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Employee Api V1");
            }
                );

then finally run your app

and type just like:
http://localhost:60855/swagger/

how to use inmemory database in aspdotnet core

Please follow the bellow steps
Step 1 -> Create your class and db context in model
 public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
    }
    public class EmployeeContext : DbContext
    {
        public EmployeeContext(DbContextOptions<EmployeeContext> dbContextOptions):base(dbContextOptions)
        {           
        }
        public DbSet<Employee> Employees { get; set; }
    }

Step2 -> In startup class add line of code in ConfigureServices method
  public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<EmployeeContext>(dbc => dbc.UseInMemoryDatabase("EmpList"));
        }

step3->add your controller and then add line of code to get all data

 [Produces("application/json")]
    [Route("api/Employee")]
    public class EmployeeController : Controller
    {
        private EmployeeContext _employeeContext;
        public EmployeeController(EmployeeContext employeeContext)
        {
            _employeeContext = employeeContext;
            if (_employeeContext.Employees.Count()==0)
            {
                _employeeContext.Employees.AddRange( new Employee { Name = "emp1" }, new Employee { Name = "emp2" });
                _employeeContext.SaveChanges();
            }
        }
        [HttpGet]
        public IEnumerable<Employee> GetAll()
        {
            return _employeeContext.Employees.AsNoTracking().ToList();
        }
    }