asp.net-coreasp.net-core-mvcroute-constraint

Custom RouteContraint with IOptions


Is there a way to pass IOptions into a custom IRouteConstraint? I'm trying to check an appsetting to see if I need to have a certain route or not.


Solution

  • Can't find any references in the moment, but

    1. either it works when you pass it in the constructor (I assume you tried it and it didn't work)
    2. get it from the HttpContext, which is passed to the Match method

    Example:

    public class MyConstraint : IRouteConstraint
    {
        public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
        {
            var options = httpContext.RequestServices.GetService<IOptions<MySettings>>();
    
            return ...;
        }
    }