You need to enable JavaScript to run this app. 如何在Asp.Net Core的Action Filter的OnActionExecuting事件中获取当前Area名称
优惠活动
大模型
产品
解决方案
定价
更多

如何在Asp.Net Core的Action Filter的OnActionExecuting事件中获取当前Area名称

Asp.Net Core Action Filter 中获取Area名称的解决方案

问题原因

ASP.NET Core 2.2 及以上版本默认启用*端点路由(Endpoint Routing)*机制后,Area信息不再默认存入RouteData.DataTokens集合,因此旧写法context.RouteData.DataTokens["area"]会返回null。

可用实现方式

  • 方案1:从RouteData的Values集合直接读取(适配绝大多数常规路由场景)
// 无Area绑定的请求返回null,注意判空
string areaName = context.RouteData.Values["area"]?.ToString();
  • 方案2:从ActionDescriptor的路由值集合读取(兼容性更高,适配属性路由、自定义路由、混合路由等特殊场景)
string areaName = null;
if (context.ActionDescriptor.RouteValues.TryGetValue("area", out var areaValue))
{
    areaName = areaValue?.ToString();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 07:33:03