AdrianStrugala / SolTechnology.Core

Modern redable coding - TaleCode foundation
5 stars 1 forks source link

Run middleware/filters only on specific endpoints #25

Closed adrian-strugala-mastercard closed 1 week ago

adrian-strugala-mastercard commented 2 weeks ago

To have the control over where this logic is applied, do not register middleware/filters for all of the apps in Startup.

Do Controller attribute and code like this:

`public class CustomObjectResultFilter : IAsyncResultFilter { public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next) { if (context.Result is ObjectResult objectResult) { var executor = context.HttpContext.RequestServices.GetRequiredService();

        var actionContext = new ActionContext
        {
            HttpContext = context.HttpContext,
            RouteData = context.RouteData,
            ActionDescriptor = context.ActionDescriptor,
            ModelState = context.ModelState
        };

        await executor.ExecuteAsync(actionContext, objectResult);
        return;
    }

    await next();
}

}

[Route("api/[controller]")] [ApiController] public class MyController : ControllerBase { [HttpGet("endpoint1")] [ServiceFilter(typeof(CustomObjectResultFilter))] public IActionResult Endpoint1() { var data = new { Message = "This is endpoint 1" }; return Ok(data); }

[HttpGet("endpoint2")]
public IActionResult Endpoint2()
{
    var data = new { Message = "This is endpoint 2" };
    return Ok(data);
}

}`