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.
Asked
Active
Viewed 101 times
1 Answers
1
Can't find any references in the moment, but
- either it works when you pass it in the constructor (I assume you tried it and it didn't work)
- get it from the
HttpContext
, which is passed to theMatch
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 ...;
}
}

Tseng
- 61,549
- 15
- 193
- 205
-
I did try it in the constructor. I'll try grabbing it from the httpContext. Thanks! – Jason N. Gaylord Oct 13 '16 at 00:35
-
Doesn't seem to be working. I can't specify the type. Still looking. – Jason N. Gaylord Oct 13 '16 at 00:43
-
Got it. Here's what I did: `... var options = httpContext.RequestServices.GetService(typeof(IOptions
)); ...` – Jason N. Gaylord Oct 13 '16 at 00:45 -
I prefer the generic versions where possible. For it you need to add a `using Microsoft.Extensions.DependencyInjection;` to make the generic extension methods available – Tseng Oct 13 '16 at 10:05