1

I'm trying to retrieve the int id = (int)WebSecurity.CurrentUserId inside the RouteConfig.cs. The id is used in an entity framework so that I'll know which controller to limit the user by using routes.IgnoreRoute() but the id gives me a

System.NullReferenceException

I'm trying to use this instead of Attribute to avoid placing/misplacing it in each/some controller.

MarcinWolny
  • 1,600
  • 2
  • 27
  • 40
Ryan G
  • 71
  • 1
  • 11
  • Related: [What is a `NullReferenceException` and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Soner Gönül Mar 10 '15 at 09:24
  • it give you null because ruteConfig class get execute in App_start event that is the event fire once when first page request come and other thing is no user logged into system at that time – Pranay Rana Mar 10 '15 at 09:24

1 Answers1

2

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

haim770
  • 48,394
  • 7
  • 105
  • 133
  • I've used a breakpoint aligned to `if (!WebSecurity.Initialized)` but when I start debugging the program it didn't stopped here. – Ryan G Mar 11 '15 at 02:32
  • @Aikitchi, I made a mistake in the constraint registration. The correct syntax is `constraints: new { CheckUserId = new CheckUserIdRouteConstraint() }`. See revised answer. – haim770 Mar 11 '15 at 17:17