Search code examples
asp.net-coreattributesasp.net-core-webapi

How can I define a custom attribute in ASP.NET Core Web API for endpoints and return an ObjectResult in it?


I am creating an ASP.NET Core Web API project. I want to define an attribute (for example ExampleAttribute) and access the HttpContext in it and doing some action and finally return an ObjectResult if necessary, or continue.

I don't know if I am doing it right or not, but I want to define an attribute in this way:

    public class DeveloperTaskAttribute : Attribute
    {
        // using HttpContext and doing some action

        // I will returning BadRequest("") if necessary
        // or continue...
    }

And I'm trying to use this attribute on this endpoint:

    [HttpGet]
    [ExampleAttribute] // using attribute
    public IActionResult EndPoint1() 
    {      
        // doing some action in endpoint1
    }

How can I do this?

Thanks for any help.


Solution

  • You need to use ActionFilterAttribute Only:

    Defining a new Attribute:

    
        public class TestAttribute : TypeFilterAttribute
            {
                public TestAttribute() : base(typeof(TestFilter))
                {
                }
        
                private class TestFilter : ActionFilterAttribute
                {
                    private readonly MyDbContext _myDbContext;
        
                    public TestFilter(MyDbContext myDbContext)
                    {
                        _myDbContext = myDbContext;
                    }
        
                    public override void OnActionExecuting(ActionExecutingContext context)
                    {
                        // Dont use async - await methods !
                        // Do something
                        var user= context.HttpContext.User    
                    }
                }
        
        
            }
    

    Note: You must use the word Attribute at the end of the name

    And using in controller:

            [Test]
            [HttpGet]
            [Route("Example")]
            public async Task<IActionResult> ExampleMethod()
            {}
    

    Documentation: https://www.andybutland.dev/2020/06/dependency-injection-in-aspnet-core-attributes.html