I have a problem with adding endpoint to controller with Route. Can someone help me? Here is the code of Program.cs I am getting this error :
System.InvalidOperationException: Unable to resolve service for type 'Swashbuckle.AspNetCore.Swagger.ISwaggerProvider' while attempting to Invoke middleware 'Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware'. at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.GetService(IServiceProvider sp, Type type, Type middleware) at lambda_method1(Closure , Object , HttpContext , IServiceProvider ) at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.<>c__DisplayClass5_1.b__2(HttpContext context) at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DBConnection")));
//Link interfaces with classes
builder.Services.AddScoped<IDepartmentRepository, DepartmentRepository>();
builder.Services.AddScoped<IEmployeeRepository, EmployeeRepository>();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Here is the code of Controller.
[Route("api/[controller]")]// for specifing the route where this controller is accessible
[ApiController]
public class EmployeesController : ControllerBase
{
private readonly IEmployeeRepository _employeeRepository;
public EmployeesController(IEmployeeRepository employeeRepository)
{
_employeeRepository = employeeRepository;
}
[HttpGet]
public async Task<IActionResult> GetEmployees()
{
try
{
return Ok(await _employeeRepository.GetEmployees());
}catch(Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, "Error retrieving data from the database");
}
}
}
You are missing AddSwaggerGen()
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();