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

ActionFilter重定向到指定URL时提示localhost重定向次数过多

问题根因

出现重定向次数过多的报错,核心原因是触发了重定向死循环:

  • 你实现的Action Filter会在对应作用域的所有Action执行前运行
  • 当供应商未激活的条件命中时,逻辑会把请求重定向到VendorActivation/CheckVendorDate
  • 但这个重定向后的目标请求,同样会被你的Action Filter拦截,再次触发相同的重定向规则
  • 循环重定向超过浏览器允许的最大次数后,就会抛出对应错误
修复方法

在执行重定向逻辑前,先判断当前请求是否已经是重定向的目标地址,如果是就直接跳过校验,避免重复跳转。
你补充的获取当前控制器、Action名称的代码正好可以用上,修正后的完整过滤器代码如下:

public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
    // 读取当前请求对应的控制器、Action信息
    var descriptor = context?.ActionDescriptor as ControllerActionDescriptor;
    if (descriptor == null)
    {
        return;
    }
    var currentActionName = descriptor.ActionName;
    var currentControllerName = descriptor.ControllerName;

    // 当前请求已经是跳转目标页时,直接跳过校验逻辑,切断循环
    if (currentActionName.Equals("CheckVendorDate", StringComparison.OrdinalIgnoreCase)
        && currentControllerName.Equals("VendorActivation", StringComparison.OrdinalIgnoreCase))
    {
        return;
    }

    var customer = await _workContext.GetCurrentCustomerAsync();
    var vendor = _vendorRepository.GetAll()
        .FirstOrDefault(w => w.CustomerId == customer.VendorId);
    if (vendor == null)
    {
        return;
    }

    // 注意:原代码判断逻辑写反了,以下为修正逻辑:已过激活时间则正常放行,未到激活时间才跳转
    if (vendor.ActivationDate < DateTime.Now)
    {
        return;
    }

    RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
    redirectTargetDictionary.Add("action", "CheckVendorDate");
    redirectTargetDictionary.Add("controller", "VendorActivation");

    context.Result = new RedirectToRouteResult(redirectTargetDictionary);
}
其他可选实现方式

除了在过滤器内判断当前请求地址,还可以用以下方式规避死循环:

  • 给CheckVendorDate Action添加跳过过滤器的标记(比如自定义特性,授权过滤器可直接用AllowAnonymous特性),在过滤器逻辑中检测到当前Action有对应标记时直接跳过
  • 不要全局注册这个过滤器,只给需要做供应商激活校验的控制器/Action单独标注,把重定向目标的Action排除在过滤器作用域外

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 19:21:27