Web API:如何从 HttpContext 读取操作属性和参数

use*_*357 6 httpcontext routedata asp.net-web-api actioncontext asp.net-web-api2

在常规课程中,我需要阅读以下内容HttpContext

  1. 控制器和操作名称

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

  3. 阅读论证(例如actionContext.ActionArguments["paramName"],但同样 - 我只有一个HttpContext

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

小智 9

来自asp.net core 3.0 /sf/answers/4242197991/

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>();
}
Run Code Online (Sandbox Code Playgroud)