0

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.

Jonesopolis
  • 25,034
  • 12
  • 68
  • 112

1 Answers1

1

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();
});
Jonesopolis
  • 25,034
  • 12
  • 68
  • 112