You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core MVC控制器方法无法访问(Angular集成场景)

.NET Core MVC与Angular集成时控制器接口404问题解决

问题现象

  • 单独创建空ASP.NET Core Web App(MVC)项目时,控制器的公共方法可正常访问;但在与Angular集成的MVC项目中,访问控制器接口出现404错误,怀疑问题出在SPA代理配置
  • 尝试过两种控制器路由写法,均无法解决404问题:
    写法1:
    [Route("authentication")]
    public class AuthenticationController : Controller
    {
        [HttpGet("example")]
        public IActionResult Example()
        {
            return Ok("This is the Welcome action method...");
        }
    }
    
    写法2:
    [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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 13:03:27