首页 > 解决方案 > Web API:如何从 HttpContext 读取动作属性和参数

问题描述

在普通课堂上,我需要阅读以下内容HttpContext

  1. 控制器和动作名称

  2. 动作的属性(我可以通过HttpActionContext.ActionDescriptor.GetCustomAttributes<type>() 但在这里我没有HttpActionContext- 我只有HttpContext

  3. 阅读论点(例如actionContext.ActionArguments["paramName"],但又一次 - 我只有一个HttpContext

它不是动作过滤器,也不是控制器类。但是,我可以访问HttpContext.

标签: asp.net-web-apiasp.net-web-api2httpcontextactioncontextroutedata

解决方案


来自asp.net core 3.0 https://stackoverflow.com/a/60602828/10612695

public async Task Invoke(HttpContext context)
{
    // Get the enpoint which is executing (asp.net core 3.0 only)
    var executingEnpoint = context.GetEndpoint();

    // Get attributes on the executing action method and it's defining controller class
    var attributes = executingEnpoint.Metadata.OfType<MyCustomAttribute>();

    await next(context);

    // Get the enpoint which was executed (asp.net core 2.2 possible after call to await next(context))
    var executingEnpoint2 = context.GetEndpoint();

    // Get attributes on the executing action method and it's defining controller class
    var attributes2 = executingEnpoint.Metadata.OfType<MyCustomAttribute>();
}

推荐阅读