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

ASP.NET MVC中如何将未识别请求路由至指定控制器方法

解决API Broker请求重定向问题的方案

看起来你现在的核心问题是:前端请求的路径(比如/getClients)没有匹配到Broker的路由规则,导致直接返回错误,根本没机会进入RedirectApi()方法执行逻辑。下面一步步帮你搞定这个问题:


1. 先修复路由配置,让所有GET请求都指向RedirectApi

当前的默认路由规则{controller=Redirect}/{action=RedirectApi}/{id}只匹配带控制器和动作名称的路径,但前端直接请求/getClients时,路由无法匹配,直接抛出404。我们需要添加一个通配路由来捕获所有GET请求:

public static void RegisterRoutes(RouteCollection routes) {
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
    // 新增:匹配所有GET请求,不管路径是什么
    routes.MapRoute(
        name: "CatchAllGet",
        url: "{*operation}", // 用通配符捕获任意请求路径
        defaults: new { controller = "Redirect", action = "RedirectApi" },
        constraints: new { httpMethod = new HttpMethodConstraint("GET") } // 只处理GET请求
    );

    // 保留默认路由作为 fallback
    routes.MapRoute(
        name: "Default",
        url: "{controller=Redirect}/{action=RedirectApi}/{id}"
    );
}

这个路由会优先匹配所有GET请求,把任何路径(比如/getClients、/getOrders)都导向Redirect控制器的RedirectApi方法,并且会把请求路径作为operation参数传给方法。

2. 修改RedirectApi方法适配路由参数

把方法改成接收路由传来的operation参数,同时调整返回类型更灵活(方便后续扩展转发逻辑):

[System.Web.Http.AcceptVerbs("GET")]
[System.Web.Http.HttpGet]
public ActionResult RedirectApi(string operation) {
    // 这里可以拿到前端请求的操作名,比如"getClients"
    // 后续如果需要转发到真实API,可以在这里添加HttpClient逻辑
    
    Customer t = dbProducts.Customers
        .Where(h => h.customerID == 1)
        .FirstOrDefault();
    return Json(t, JsonRequestBehavior.AllowGet);
}

注意:确保你的控制器类名是RedirectController(因为路由里指定的控制器是Redirect),否则路由找不到对应的控制器。

3. 修复过滤器的空引用问题

当前过滤器里直接调用actionContext.Request.Headers.GetValues("loggedinUser").First(),如果请求头没有这个字段会直接抛出空引用错误,导致请求提前失败。修改成安全的写法:

public override void OnActionExecuting(HttpActionContext actionContext) {
    if (actionContext.Request.Method.Method == "GET")
    {
        IEnumerable<string> userHeaders;
        // 先检查请求头是否存在
        if (actionContext.Request.Headers.TryGetValues("loggedinUser", out userHeaders))
        {
            string loggedInUser = userHeaders.FirstOrDefault();
            if (!string.IsNullOrEmpty(loggedInUser))
            {
                // 这里添加你的验证/业务逻辑
            }
        }
        // 可选:如果缺少头,直接返回错误
        // else
        // {
        //     actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "Missing loggedinUser header");
        //     return;
        // }
    }
    base.OnActionExecuting(actionContext);
}

4. 测试验证

现在前端调用http://localhost:54857/getClients时,路由会匹配到我们新增的CatchAllGet规则,进入RedirectApi方法执行逻辑,不会再直接报错。


内容的提问来源于stack exchange,提问作者NielsStenden

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:31:37