.NET Core MVC控制器方法无法访问(Angular集成场景)
.NET Core MVC与Angular集成时控制器接口404问题解决
问题现象
- 单独创建空ASP.NET Core Web App(MVC)项目时,控制器的公共方法可正常访问;但在与Angular集成的MVC项目中,访问控制器接口出现404错误,怀疑问题出在SPA代理配置
- 尝试过两种控制器路由写法,均无法解决404问题:
写法1:
写法2:[Route("authentication")] public class AuthenticationController : Controller { [HttpGet("example")] public IActionResult Example() { return Ok("This is the Welcome action method..."); } }[Route("[controller]")] public class AuthenticationController : Controller { [HttpGet("example")] public IActionResult Example() { return Ok("This is the Welcome action method..."); } } - 访问
localhost:PORT/authentication/example时返回404,项目未使用独立API,需在MVC+Angular的混合应用中调用控制器的GET/POST接口 - 当前Program.cs配置如下:
var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllersWithViews(); var app = builder.Build(); app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); app.Run();
解决方法
修改Angular项目中的proxy.conf.js文件,在代理配置的context数组中添加目标路由/authentication:
const PROXY_CONFIG = [ { context: [ "/weatherforecast", "/authentication" ], target: target, secure: false, headers: { Connection: 'Keep-Alive' } } ]
内容的提问来源于stack exchange,提问作者Anil
相关产品推荐
相关产品推荐

