ASP.NET Core MVC启动服务器时出现Error 404问题求助
问题:ASP.NET Core API路由404错误
开发兽医诊所管理系统服务器,医生可通过Web应用登录个人账户并查看排班。已编写模型、视图和控制器代码,但启动服务器时出现HTTP ERROR 404,访问/api或/doctor/login均无效。项目无默认Startup文件,系手动创建,怀疑路由或Startup配置有误。
代码片段:DoctorsController
using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System.Linq; using System.Threading.Tasks; using VetCareServ.Data; using VetCareServ.DTO; using VetCareServ.Models; [Route("api/[controller]")] [ApiController] public class DoctorsController : ControllerBase { private readonly VetCareServDbContext _context; public DoctorsController(VetCareServDbContext context) { _context = context; } [HttpPost("login")] public async Task<IActionResult> Login([FromBody] DoctorLoginModel doctorLogin) { if (ModelState.IsValid) { var authenticatedDoctor = await _context.DoctorLoginModel .FirstOrDefaultAsync(d => d.DoctorEmail == doctorLogin.DoctorEmail && d.DoctorPassHash == doctorLogin.DoctorPassHash); if (authenticatedDoctor != null) { var doctorInfo = await _context.Doctors .FirstOrDefaultAsync(d => d.DoctorEmail == doctorLogin.DoctorEmail); return RedirectToAction("Account", new { id = doctorInfo.DoctorId }); } else { ModelState.AddModelError(string.Empty, "Неверные учетные данные"); return BadRequest(ModelState); } } return BadRequest(ModelState); } [HttpGet("account/{id}")] public async Task<IActionResult> Account(int id) { var doctor = await _context.Doctors.FindAsync(id); if (doctor == null) { return NotFound(); } return Ok(doctor); } }
代码片段:Startup.cs
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using VetCareServ.Data; namespace VetCareServ { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddDbContext<VetCareServDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddControllersWithViews(); services.AddSession(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseSession(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Doctor}/{action=Login}/{id?}");//it seems to be right! }); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } }
解决方案与优化建议
一、修复Startup配置中的核心问题
- 修正中间件顺序:ASP.NET Core中间件必须按固定顺序执行,当前
UseEndpoints调用在UseRouting、UseHttpsRedirection之前,会导致路由逻辑失效。正确顺序为:异常处理 → HSTS → HTTPS重定向 → 静态文件 → Session → 路由 → 授权 → 端点映射。 - 合并并修正路由配置:代码中重复配置同名默认路由,且未单独映射API控制器。修改后的
Configure方法如下:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseSession(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { // 优先映射API控制器(支持属性路由) endpoints.MapControllers(); // 配置MVC页面默认路由 endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); }
二、修正API访问路径
你的DoctorsController使用属性路由[Route("api/[controller]")],正确的访问路径应为:
- 登录接口:
POST /api/Doctors/login(控制器名称为复数Doctors,而非doctor) - 账户信息接口:
GET /api/Doctors/account/{id}
三、API逻辑优化
- 移除API中的重定向逻辑:REST API应返回JSON数据而非页面重定向,前端收到成功响应后自行处理跳转逻辑。修改
Login方法:
[HttpPost("login")] public async Task<IActionResult> Login([FromBody] DoctorLoginModel doctorLogin) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var authenticatedDoctor = await _context.DoctorLoginModel .FirstOrDefaultAsync(d => d.DoctorEmail == doctorLogin.DoctorEmail && d.DoctorPassHash == doctorLogin.DoctorPassHash); if (authenticatedDoctor == null) { ModelState.AddModelError(string.Empty, "Неверные учетные данные"); return Unauthorized(ModelState); // 使用401状态码更符合REST规范 } var doctorInfo = await _context.Doctors .FirstOrDefaultAsync(d => d.DoctorEmail == doctorLogin.DoctorEmail); if (doctorInfo == null) { return NotFound("医生信息不存在"); } return Ok(new { DoctorId = doctorInfo.DoctorId, DoctorInfo = doctorInfo }); }
- 密码安全优化:建议使用ASP.NET Core内置的
PasswordHasher<T>进行密码哈希与验证,避免直接比较哈希值的安全风险。
四、其他排查要点
- 确认
VetCareServDbContext中的DoctorLoginModel和Doctors集合已正确映射到数据库表。 - 开发环境下保留
UseDeveloperExceptionPage,可查看详细错误堆栈信息,快速定位问题。
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

