How to add metadata to ASP.NET endpoint

Viewed 991

I have a basic endpoint:

    [HttpGet]
    [MyAttribute]
    public string Get()
    {
      // Do stuff
    }

And a basic middleware:

  public class MyMiddleware  : IMiddleware
  {
    
    public Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
      var endpoint = context.GetEndpoint();
      var metadata = endpoint.Metadata;
      if (metadata.GetMetadata<MyAttribute>() != null)
      {
        // Do stuff 
      }
      return next(context);
    }
  }

I would like to have the middleware be contextually aware of the [MyAttribute] but it does not show up in the endpoint metadata. How can I achieve this?

1 Answers

You can achieve this with Middleware by doing the following:

public class MyMiddleware : IMiddleware
{
    public Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        var endPoint = context.GetEndpoint();
        var attribute = endPoint?.Metadata.OfType<MyAttribute>();

        if(attribute != null)
        {
            // Do stuff
        }

        return next(context);
    }
}

Make sure you register your Middleware class in the right position in the pipeline - otherwise endpoint could end up being null.

Related