user3711357
user3711357

Reputation: 1625

Web API: how to read action attribute and parameters from HttpContext

In regular class, I need to read following from the HttpContext:

  1. Controller and action name

  2. Action's attribute (I could get that through HttpActionContext.ActionDescriptor.GetCustomAttributes<type>() but here I don't have HttpActionContext - I only have HttpContext)

  3. Read argument (like actionContext.ActionArguments["paramName"], but again - I only have a HttpContext)

It's not an action filter and not a controller class. But, I can access HttpContext.

Upvotes: 8

Views: 6535

Answers (1)

Maik van den Hengel
Maik van den Hengel

Reputation: 371

From 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>();
}

Upvotes: 14

Related Questions