How to add metadata to ASP.NET endpoint

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x