0

I have created a Rest API that works (its returning the data I expect in postman).

But when I try to go the swagger part I get this error:

Fetch error undefined /swagger/v1/swagger.json

Swagger Error Message:

enter image description here

Here is the code in my startup class

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddSwaggerGen(c =>
   {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "TP_Service", Version = "v1" });
     });
    services.AddDbContext<CommandContext>(opt =>
    opt.UseSqlServer(Configuration["Data:CommandAPIConnection:ConnectionString"]));
    services.AddMvc(option => option.EnableEndpointRouting = 
    false).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
}

and

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment() || env.IsProduction())
    {
        app.UseDeveloperExceptionPage();
        app.UseSwagger();
        app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "TestApi v1"));
    }
   app.UseMvc();

   app.UseHttpsRedirection();

   app.UseRouting();

   app.UseAuthorization();

   app.UseEndpoints(endpoints =>
   {
      endpoints.MapControllers();
   });
}

What have I done wrong to make it not work. (It does when I run the Code on IIS Express)

using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TP_Service.Models;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace TP_Service.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ServiceController : ControllerBase
    {

        private readonly CommandContext _context;

        public ServiceController(CommandContext context)
        {
            _context = context;
        }


        // GET: api/<ServiceController>
        [HttpGet]
        public ActionResult<IEnumerable<Service>> GetServices()
        {
            return _context.Services;
        }

        // GET api/<ServiceController>/5
        [HttpGet("{id}")]
        public ActionResult<ServiceVM> GetServiceDetails(int id)
        {
            ServiceVM serviceVM = new ServiceVM();

            serviceVM.service = _context.Services.Find(id);
            serviceVM.ServiceTaskList = _context.ServiceTasks.Select(
                                                x => new ServiceTask()
                                                {
                                                    Id = x.Id,
                                                    ServiceId = x.ServiceId,
                                                    CurrentAssemblyID = x.CurrentAssemblyID,
                                                    CurrentAssemblyName = x.CurrentAssemblyName,
                                                    TaskName = x.TaskName,
                                                    TaskQuoteName = x.TaskQuoteName,
                                                    TaskDescription = x.TaskDescription,
                                                    Notes = x.Notes,
                                                    ServiceTaskPartList = _context.ServiceTaskParts.Select(
                                                        x => new ServiceTaskPart()
                                                        {
                                                            Id = x.Id,
                                                            TaskId = x.TaskId,
                                                            PartId = x.PartId,
                                                            PartName = x.PartName,
                                                            QtyNeeded = x.QtyNeeded,
                                                            QtyUsed = x.QtyUsed,
                                                            QtyReturned = x.QtyReturned,
                                                            QtyLeftOnSite = x.QtyLeftOnSite
                                                        }
                                                    ).Where(STP => STP.TaskId == x.Id).ToList()
                                                }
                                                ).Where(ST => ST.ServiceId == id).ToList();


            return serviceVM;
        }


    //// POST api/<ServiceController>
    //[HttpPost]
    //    public void Post([FromBody] string value)
    //    {
    //    }

    //    // PUT api/<ServiceController>/5
    //    [HttpPut("{id}")]
    //    public void Put(int id, [FromBody] string value)
    //    {
    //    }

    //    // DELETE api/<ServiceController>/5
    //    [HttpDelete("{id}")]
    //    public void Delete(int id)
    //    {
    //    }
    //}
}
  • Check your action methods. Maybe you have duplicate routes somewhere. For example, the route of one method is `api/items` If there's another method also using the same route, swagger is not going to open. – Qudus May 28 '21 at 06:30
  • 1
    Here is your puzzled solved, might be your desired solution. [LINK](https://stackoverflow.com/questions/56859604/swagger-not-loading-failed-to-load-api-definition-fetch-error-undefined) – Pashyant Srivastava May 28 '21 at 16:48
  • It's most likely an error in your controller. Can you post the entire Controller code? – Andy May 28 '21 at 18:52
  • I have added the controller to the submission – Frostie8467 May 29 '21 at 04:58

2 Answers2

1

Try to navigate to https://localhost:{PortNo}/swagger/v1/swagger.json. You will noticed if there is any issue with the api configuration.

Also you can open network tab in dev tools and looking for the response for swagger. Json

Also check your api routes as well. Seems like you have two http get methods, to support that you have to change route config if you have not already done.

Darshani Jayasekara
  • 561
  • 1
  • 4
  • 14
0

Well check this part

  • check if you didn't duplicated methods
  • Check that your project xml document is enable ( in project properties)
  • check all the necessary nuget install ( I included them here)

nugets for swagger

  • Swashbuckle.AspNetCore
  • Swashbuckle.AspNetCore.Swagger
  • Swashbuckle.AspNetCore.SwaggerGen
  • Swashbuckle.AspNetCore.SwaggerUI
Reza Faghani
  • 141
  • 1
  • 10