swagger ASP.NET Core Web API:无法到达任何终点

qq24tv8q  于 8个月前  发布在  .NET
关注(0)|答案(2)|浏览(111)

我正在使用.NET 6.0,无法执行任何控制器方法。我回去创建了我能想到的最简单的控制器,它也不起作用。Swagger采用了我创建的所有控制器和方法,包括更复杂的控制器和方法。但是当我执行其中任何一个时,我得到一个404错误。如果我直接将URL粘贴到浏览器中,我会得到同样的错误。但是,服务正在运行。
我花了三天时间想弄明白为什么。但没有任何进展。
下面是我的简单控制器:

using Microsoft.AspNetCore.Mvc;

namespace CoreWebAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class testController : ControllerBase
    {
        [HttpGet]
        public IActionResult Get()
        {
            // Replace this with the string you want to return
            string responseString = "Hello, World!";

            // Return the string as an OK response
            return Ok(responseString);
        }
    }
}

以下是我的程序类:

using Microsoft.EntityFrameworkCore;
using System;
using CoreWebAPI;
using Microsoft.Extensions.DependencyInjection;
using CoreWebAPI.Data.DBContexts;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace CoreWebAPI
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

下面是我的Startup类:

using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Reflection;
using Microsoft.EntityFrameworkCore;
using CoreWebAPI.Data.DBContexts;
using CoreWebAPI.Mapings;
using AutoMapper;

namespace CoreWebAPI
{
    public class Startup
    {
        public IConfiguration Configuration { get; }

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            // Configure services here
            services.AddDbContext<BuzzAlertDBContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("HomeConnection")!)); ;

            services.AddControllers();

            services.AddAutoMapper(typeof(Startup));
            services.AddAutoMapper(typeof(AutoMappingProfile));

            // add swagger
            services.AddSwaggerGen(c =>
            {
                // Define your Swagger documentation version and title
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "CoreWebAPI", Version = "v1" });

                // Enable XML comments (if you have XML documentation)
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                //c.IncludeXmlComments(xmlPath);
            });
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            // Other app configurations

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();

                // Enable Swagger UI only in development mode
                app.UseSwagger();
                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "CoreWebAPI");
                    c.EnableValidator(null);
                });
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            // Other app configurations
        }
    }
}

也许我在项目设置中错过了一些基本的东西。但我看不见。
谢谢你的帮助。
Erick

cdmah0mi

cdmah0mi1#

尝试创建默认Web应用程序并比较启动代码:你会看到一些差异。
主要区别是使用了错误的构建器,您应该使用WebApplicationBuilder,它使您能够进一步配置您的应用程序以正确工作。
我也没有看到调用services.AddEndpointsApiExplorer();
因此,下面我附上了正确的Program.cs文件,现在可以正确运行(我移动了方法Startup-您可以比较它们的实现:

public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        // Add services to the container.
        ConfigureServices(builder.Services);

        var app = builder.Build();

        Configure(app, builder.Environment);

        app.UseHttpsRedirection();

        app.UseAuthorization();

        app.MapControllers();

        app.Run();
    }

    public static void ConfigureServices(IServiceCollection services)
    {
        // Configure services here
        //services.AddDbContext<BuzzAlertDBContext>(options =>
        //    options.UseSqlServer(Configuration.GetConnectionString("HomeConnection")!)); ;

        services.AddControllers();

        //services.AddAutoMapper(typeof(Startup));
        //services.AddAutoMapper(typeof(AutoMappingProfile));

        // add swagger
        services.AddSwaggerGen(c =>
        {
            // Define your Swagger documentation version and title
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "CoreWebAPI", Version = "v1" });

            // Enable XML comments (if you have XML documentation)
            var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
            var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
            //c.IncludeXmlComments(xmlPath);
        });

        // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
        services.AddEndpointsApiExplorer();
        services.AddSwaggerGen();
    }

    public static void Configure(WebApplication app, IWebHostEnvironment env)
    {
        // Other app configurations

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();

            // Enable Swagger UI only in development mode
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "CoreWebAPI");
                c.EnableValidator(null);
            });
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }

        // Other app configurations
    }
}

然后将TestController添加到Controllers项目目录中即可正常工作:

rlcwz9us

rlcwz9us2#

除非这是在“其他应用程序配置”下,否则您将错过一个调用,如app.MapControllers(),它将控制器的路由添加到中间件管道中。

相关问题