Search code examples
c#asp.net-mvc.net-6.0attributerouting

Validate Route Parameter by Name across many endpoints


In a .NET 6 MVC app, I have a lot of endpoints attributed similar to:

[HttpGet("getCustomerItem/{customerNumber:int}/{itemNumber:int}")]
public async Task<IActionResult> GetCustomerItem([FromRoute] int customerNumber, [FromRoute] int itemNumber)

This is across several controllers, the main thing being the route parameter I'm concerned with is always called customerNumber. I want to do some validation against that for each endpoint, to ensure the user has access to that customer.

Is there a way I can add middleware that checks if the endpoint has a route parameter called customerNumber and, if so, get the value coming in to validate it? I think this is possible, but I cannot recall the correct terminology.


Solution

  • Well this was easier than I was thinking it would be. Turns out I could get the RouteData directly from the context. Added this just before MVC in the pipeline -

    app.Use(async (ctx, next) =>
    {
         var customerNumberObject = ctx.GetRouteValue("customerNumber");
    
         if (customerNumberObject != null && int.TryParse(customerNumberObject.ToString(), out var customerNumber))
         {
            if (/* failed validation */)
            {
                ctx.Response.Redirect("/error");
            }
         }
    
        await next();
    });