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

Tom*_*Tom 6 swagger asp.net-core

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

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

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

/swagger/v1/swagger.json
../swagger/v1/swagger.json
v1/swagger.json
Run Code Online (Sandbox Code Playgroud)

启动.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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

客户控制器

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



}
Run Code Online (Sandbox Code Playgroud)

Tod*_*nce 5

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

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

    [HttpGet("id")]
    [ProducesResponseType(typeof(string), 200)]
    [ProducesResponseType(500)]
    [Route("{employeeID:int}")]
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


小智 3

您收到错误消息。因为你把你的动作名称加倍了。查看此示例。\n Swagger \xe2\x80\x93 无法加载 API 定义,请更改 [Route("GetCustomers")]名称并重试。

\n