Routes registration is performed early upon Application_Start
. At this stage, WebSecurity
is not initialized yet (and even if it were, it knows nothing about the current user because there is no Request
yet), so you cannot use it this way.
If you insist relying on WebSecurity
for routes resolving, you can use a RouteConstraint
that will be checked upon actually requesting that route so you'll have an HTTP Request
and authenticated / non-authenticated user in-tact.
For example:
public class CheckUserIdRouteConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
if (!WebSecurity.Initialized)
return false;
var userId = WebSecurity.CurrentUserId;
// check your user id
return userId == 1;
}
}
Then attach the constraint to your route registration. For example:
routes.MapRoute(
name: "SomeRoute",
url: "SomeRoute/{action}",
defaults: new { controller = "MyCtrl", action = "Index" },
constraints: new { CheckUserId = new CheckUserIdRouteConstraint() }
);
See MSDN