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

.NET 6/.NET Core中ActionNameSelectorAttribute的替代方案及适配方法

适配.NET 6的MultiBtnAttribute替代实现

ASP.NET Core(.NET 6+)已移除.NET Framework中的ActionNameSelectorAttribute,以下是改动量极小的兼容方案,基于ActionMethodSelectorAttribute实现原逻辑:

修改后的代码

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MultiBtnAttribute : ActionMethodSelectorAttribute
{
    public string Name { get; set; }
    public string Value { get; set; }

    public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor actionDescriptor)
    {
        var httpContext = routeContext.HttpContext;
        var keyValue = $"{Name}:{Value}";
        
        // 从表单或查询字符串中获取对应值,兼容原ValueProvider逻辑
        string value = null;
        if (httpContext.Request.Form.ContainsKey(keyValue))
        {
            value = httpContext.Request.Form[keyValue].ToString();
        }
        else if (httpContext.Request.Query.ContainsKey(keyValue))
        {
            value = httpContext.Request.Query[keyValue].ToString();
        }

        if (!string.IsNullOrEmpty(value))
        {
            // 保持原逻辑:将值存入RouteData供后续使用
            routeContext.RouteData.Values[Name] = value;
            return true;
        }

        return false;
    }
}

关键改动说明

  • 基类替换:用ASP.NET Core官方提供的ActionMethodSelectorAttribute替代已废弃的ActionNameSelectorAttribute,二者功能定位一致
  • 请求数据获取:直接通过HttpContext读取表单/查询字符串数据,替代原ValueProvider的调用方式(ASP.NET Core中已不再通过Controller实例暴露ValueProvider)
  • RouteData赋值:直接操作RouteContext.RouteData,替代原ControllerContext.RouteData的逻辑,保持后续业务代码的兼容性

额外注意

如果原应用中按钮提交的是标准的name="xxx" value="yyy"格式(而非Name:Value作为键),可调整值判断逻辑为:

var formValue = httpContext.Request.Form[Name];
if (!string.IsNullOrEmpty(formValue) && formValue == Value)
{
    routeContext.RouteData.Values[Name] = Value;
    return true;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 16:37:36