ASP.NET Core Web API端点访问遇HTTP Error 404问题求助
创建新的ASP.NET Core Web API项目后,在开发环境运行时出现HTTP Error 404. This localhost page can't be found.错误。尝试在Program.cs和ServiceExtension.cs中设置断点调试,但程序并未进入控制器类和服务类。
Program.cs 代码
var builder = WebApplication.CreateBuilder(args); // Including the path for configuration file for the NLog configuration. LogManager.LoadConfiguration(string.Concat(Directory.GetCurrentDirectory(), "/nlog.config")); // Add services to the container. builder.Services.ConfigureCors(); builder.Services.ConfigureIISIntegration(); builder.Services.ConfigureLoggerService(); builder.Services.ConfigureSqlContext(builder.Configuration); builder.Services.ConfigureRepositoryManager(); builder.Services.ConfigureServiceManager(); builder.Services.AddControllers().AddApplicationPart(typeof(CompanyEmployees.Presentation.AssemblyReference).Assembly); var app = builder.Build(); if(app.Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } // Configure the HTTP request pipeline. app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.All }); app.UseCors("CorsPolicy"); app.UseAuthorization(); app.MapControllers(); app.Run();
ServiceExtension.cs 代码
namespace CompanyEmployees.Extensions { public static class ServiceExtensions { public static void ConfigureCors(this IServiceCollection services) => services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()); }); public static void ConfigureIISIntegration(this IServiceCollection services) => services.Configure<IISOptions>(options => { //We are not adding any options becasue we are configuring for default ones }); public static void ConfigureLoggerService(this IServiceCollection services) => services.AddSingleton<ILoggerManager, LoggerManager>(); public static void ConfigureRepositoryManager(this IServiceCollection services) => services.AddScoped<IRepositoryManager, RepositoryManager>(); public static void ConfigureServiceManager(this IServiceCollection services) => services.AddScoped<IServiceManager, ServiceManager>(); public static void ConfigureSqlContext(this IServiceCollection services, IConfiguration configuration) => services.AddDbContext<RepositoryContext>(opts => opts.UseSqlServer(configuration.GetConnectionString("sqlconnection"))); } }
控制器类代码
namespace CompanyEmployees.Presentation.Controllers { [Route("api/companies")] [ApiController] public class CompaniesController : ControllerBase { private readonly IServiceManager _serviceManager; public CompaniesController(IServiceManager serviceManager) { _serviceManager = serviceManager; } [HttpGet] public IActionResult GetCompanies() { try { var companies = _serviceManager.CompanyService.GetAllCompanies(trackChanges: false); return Ok(companies); } catch { return StatusCode(500, "Internal Server Error"); } } } }
确认控制器程序集加载是否正确
代码中使用AddApplicationPart(typeof(CompanyEmployees.Presentation.AssemblyReference).Assembly)加载控制器所在程序集,需先检查AssemblyReference类是否存在于CompanyEmployees.Presentation项目中。若该类不存在,程序集无法被正确识别,控制器也不会被注册。
解决方式:要么在CompanyEmployees.Presentation项目中添加一个空的AssemblyReference类(仅用于标记程序集),要么直接替换为控制器类型获取程序集,比如typeof(CompaniesController).Assembly。验证请求地址准确性
确保访问地址为https://localhost:<端口号>/api/companies,代码中启用了UseHttpsRedirection,必须使用HTTPS协议,且不能遗漏api/companies路径。若访问根路径/,因无对应控制器,返回404属于正常现象。检查路由注册与中间件顺序
确认app.MapControllers()在UseAuthorization()之后(当前代码顺序正确),中间件顺序错误可能导致路由无法匹配。可在app.MapControllers()前添加代码,打印已注册的路由,验证控制器是否被正确发现:var endpointDataSource = app.Services.GetRequiredService<EndpointDataSource>(); foreach (var endpoint in endpointDataSource.Endpoints) { if (endpoint is RouteEndpoint routeEndpoint) { Console.WriteLine($"已注册路由: {routeEndpoint.RoutePattern.RawText}"); } }运行后查看控制台,若未出现
api/companies路由,回到第一个排查点处理程序集加载问题。排查依赖注入异常
控制器构造函数依赖的IServiceManager及其链式依赖(如IRepositoryManager、RepositoryContext)若注册失败,可能导致程序启动异常但未直观报错。可在app.Run()前添加异常捕获,或检查开发环境日志:try { app.Run(); } catch (Exception ex) { Console.WriteLine($"启动错误: {ex.Message}"); throw; }同时确认
appsettings.json中存在sqlconnection连接字符串,否则ConfigureSqlContext会导致DbContext注册失败,进而影响整个依赖链。清理并重新生成项目
编译缓存可能导致程序集加载异常,右键解决方案选择「清理」,再重新生成所有项目后运行调试。
内容的提问来源于stack exchange,提问作者Arpit Chinmay

