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

.NET 6 MVC中如何在自定义中间件读取MapControllerRoute的匿名对象

在自定义中间件中读取路由默认匿名属性的方法

可以读取你配置的路由匿名属性,但无法直接通过RouteData获取——因为RouteData仅存储从URL路径匹配到的参数,而你配置的anonymousProperty属于路由的默认值,并未作为URL的一部分,因此不会出现在RouteData中。

具体实现步骤

要获取这个属性,需要通过HttpContext的端点元数据提取:

  • 从HttpContext.Features中获取IEndpointFeature,进而拿到当前匹配的Endpoint。
  • 从Endpoint.Metadata中找到ControllerActionDescriptor实例,路由的默认值会被存储在它的RouteValues字典中。

示例代码

public class CustomMiddleware
{
    private readonly RequestDelegate _next;

    public CustomMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        var endpointFeature = context.Features.Get<IEndpointFeature>();
        var endpoint = endpointFeature?.Endpoint;

        if (endpoint != null)
        {
            var actionDescriptor = endpoint.Metadata.GetMetadata<ControllerActionDescriptor>();
            if (actionDescriptor != null && actionDescriptor.RouteValues.TryGetValue("anonymousProperty", out var propertyValue))
            {
                // 使用获取到的属性值,示例中为"3"
                Console.WriteLine($"anonymousProperty: {propertyValue}");
            }
        }

        await _next(context);
    }
}

// 注册中间件(必须放在app.UseRouting()之后)
app.UseRouting();
app.UseMiddleware<CustomMiddleware>();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        "Error",
        "error",
        new { controller = "Error", action = "Index", anonymousProperty = "3" });
});

注意事项

  • 中间件必须注册在app.UseRouting()之后,确保路由匹配完成后Endpoint已被正确赋值。
  • 该方法适用于所有路由默认值,无论是否是匿名对象中的属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 01:15:31