swagger:无法加载未定义的API定义/swagger/v1/swagger.json

时间:2019-08-18 13:27:58

标签: asp.net-core swagger

我尝试在asp.net核心api中配置swagger,并收到以下错误。无法加载未定义的API定义/swagger/v1/swagger.json

我不确定为什么会出现此错误。我已经在启动文件中添加了必要的配置

我尝试了以下路径,但没有区别

/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();
        }
    }



}

6 个答案:

答案 0 :(得分:1)

如果您在损坏的 Swashbuckle 页面上,打开开发工具...查看 Swagger 发回的 500 响应,您将获得一些深刻的见解。

这是我正在做的愚蠢的事情......在 HTTPGet 中有一个路由以及一个 ROUTE 路由。

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

enter image description here

答案 1 :(得分:0)

您遇到错误。因为您,您的动作名称增加了一倍。看这个例子。 Swagger – Failed To Load API Definition,更改[Route("GetCustomers")]名称,然后重试。

答案 2 :(得分:0)

这通常表示Swashbuckle由于某种原因不支持的控制器/动作。

预计您的项目中没有swagger.json文件。 Swashbuckle使用ASP.NET Core的ApiExplorer API动态创建并提供服务。这里可能发生的是Swashbuckle无法生成Swagger.json,因此UI无法显示。

很难确切知道是什么原因导致了故障,所以调试的最佳方法可能就是删除一半的控制器(只需将文件移到一个临时位置)并检查问题是否仍然存在。然后,您将知道哪一部分控制器包含麻烦的操作。您可以“二进制搜索”删除控制器(然后再删除操作),直到找出导致Swashbuckle无法生成Swagger.json的操作方法。一旦知道,这是代码中的问题还是应该在Swashbuckle存储库中提交的问题。

您可以按F12键打开chrome浏览器的开发人员工具以检查失败原因,然后输入失败的请求路径,然后单击错误文件以预览详细的错误。

路线模糊或与Swashbuckle绊倒等问题也可能是一个问题。将故障原因缩小到更具体的问题后,就可以根据需要修复或提出问题。

答案 3 :(得分:0)

Swagger也不能处理两个具有相同名称的类(至少不是开箱即用)。因此,如果您有两个名称空间,并且两个类具有相同的名称,则它将无法初始化。

答案 4 :(得分:0)

我知道这已经解决了,但我今天遇到了同样的问题。

就我而言,问题是我创建了一个从其他控制器继承的基本控制器类。 当我在基类上创建一个公共函数时,问题开始发生。把它变成受保护的就行了

答案 5 :(得分:0)

如果你想通过 host:port/swagger/v1/swagger.json 访问 swagger,那么你应该在里面添加 options: SwaggerGenOptions

public void ConfigureServices(IServiceCollection services)
{
    services.AddSwaggerGen(c => 
        c.SwaggerDoc("swagger/v1", new OpenApiInfo { Version = "1.0", Title = "API" });
    );
}

它应该可以正常工作。