Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swagger : Failed to load API definition undefined /swagger/v1/swagger.json

I have tried to configure swagger in my asp.net core api and getting the following error. Failed to load API definition undefined /swagger/v1/swagger.json

I am not sure why I am getting this error. I have added the necessary configuration in the startup file

I have tried the following paths but there has been no difference

/swagger/v1/swagger.json
../swagger/v1/swagger.json
v1/swagger.json

startup.cs

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.AddSwaggerGen(c =>
            {

            });


            services.AddDbContext<NorthwindContext>(item => item.UseSqlServer(Configuration.GetConnectionString("NorthwindDBConnection")));
            services.AddCors(option => option.AddPolicy("MyPolicy", builder => {
                builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();

            }));

            var mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new MappingProfile());
            });

            IMapper mapper = mappingConfig.CreateMapper();
            services.AddSingleton(mapper);



            services.AddScoped<ICustomerRepository, CustomerRepository>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            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.UseCors("MyPolicy");
            app.UseHttpsRedirection();
            app.UseSwagger();
            app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "API name"); });
            app.UseMvc();
        }
    }

CustomerController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Customer.Repository;
using CustomerService.Models;
using CustomerService.ViewModel;
using Microsoft.AspNetCore.Mvc;

namespace CustomerService.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class CustomersController : Controller
    {

        ICustomerRepository _customersRepository;


        public CustomersController(ICustomerRepository customersRepository)
        {
            _customersRepository = customersRepository;
        }

        [HttpGet]
        [Route("GetCustomers")]
        //[NoCache]
        [ProducesResponseType(typeof(List<CustomerViewModel>), 200)]
        [ProducesResponseType(typeof(ApiResponse), 400)]
        public async Task<IActionResult> Customers()
        {
            try
            {
                var customers = await _customersRepository.GetAllCustomers();
                if (customers == null)
                {
                    return NotFound();
                }

                return Ok(customers);
            }
            catch
            {
                return BadRequest();
            }
        }


        [HttpGet]
        [Route("GetCustomer")]
        //[NoCache]
        [ProducesResponseType(typeof(List<CustomerViewModel>), 200)]
        [ProducesResponseType(typeof(ApiResponse), 400)]
        public async Task<IActionResult> Customers(string customerId)
        {
            if (customerId == null)
            {
                return BadRequest();
            }

            try
            {
                var customer = await _customersRepository.GetCustomer(customerId);
                if (customer == null)
                {
                    return NotFound();
                }

                return Ok(customer);
            }
            catch
            {
                return BadRequest();
            }
        }

        [HttpPost]
        [Route("AddCustomer")]
        public async Task<IActionResult> AddCustomer([FromBody] CustomerViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var customerId = await _customersRepository.Add(model);
                    if (customerId != null)
                    {
                        return Ok(customerId);
                    }
                    else
                    {
                        return NotFound();
                    }
                }
                catch(Exception ex)
                {
                    return BadRequest();
                }
            }
            return BadRequest();
        }


        [HttpPost]
        [Route("DeleteCustomer")]
        public async Task<IActionResult> DeleteCustomer(string customerId)
        {
            int result = 0;

            if (customerId == null)
            {
                return BadRequest();
            }

            try
            {
                var customer = await _customersRepository.Delete(customerId);
                if (customer == null)
                {
                    return NotFound();
                }

                return Ok(customer);
            }
            catch
            {
                return BadRequest();
            }
        }



        [HttpPost]
        [Route("UpdateCustomer")]
        public async Task<IActionResult> UpdateCustomer([FromBody] CustomerViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    await _customersRepository.Update(model);
                    return Ok();
                }
                catch(Exception ex)
                {
                    if (ex.GetType().FullName == "Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException")
                    {
                        return NotFound();
                    }

                    return BadRequest();
                }
            }
            return BadRequest();
        }
    }



}
like image 493
Tom Avatar asked Mar 03 '23 13:03

Tom


2 Answers

Swagger also cannot deal with two Classes having the same name (at least, not out of the box). So if you have two name spaces, and two classes having the same name, it will fail to initialize.

like image 101
Egbert Nierop Avatar answered Apr 07 '23 06:04

Egbert Nierop


If you are on the broken Swashbuckle page, Open Dev Tools ... look at the 500 response that Swagger sends back and you will get some great insight.

Here's the dumb thing I was doing ... had a route in the HTTPGet as well as a ROUTE route.

    [HttpGet("id")]
    [ProducesResponseType(typeof(string), 200)]
    [ProducesResponseType(500)]
    [Route("{employeeID:int}")]

enter image description here

like image 36
Todd Vance Avatar answered Apr 07 '23 06:04

Todd Vance