C#MVC4 WebSecurity.CurrentUserId在RouteConfig.cs内

C#MVC4 WebSecurity.CurrentUserId在RouteConfig.cs内,c#,asp.net-mvc-4,C#,Asp.net Mvc 4,我正在尝试检索RouteConfig.cs中的intid=(int)WebSecurity.CurrentUserId。在实体框架中使用id,这样我就可以知道使用routes.IgnoreRoute()限制用户的控制器,但是id给了我一个 System.NullReferenceException 我尝试使用此属性而不是属性,以避免将其放置/错放在每个/某些控制器中。在应用程序启动时尽早执行路由注册。在这个阶段,WebSecurity尚未初始化(即使初始化了,它也对当前用户一无所知,因为还没有

我正在尝试检索
RouteConfig.cs
中的
intid=(int)WebSecurity.CurrentUserId
。在实体框架中使用
id
,这样我就可以知道使用
routes.IgnoreRoute()
限制用户的控制器,但是
id
给了我一个

System.NullReferenceException

我尝试使用此属性而不是属性,以避免将其放置/错放在每个/某些控制器中。

应用程序启动时尽早执行路由注册。在这个阶段,
WebSecurity
尚未初始化(即使初始化了,它也对当前用户一无所知,因为还没有
请求
),因此不能以这种方式使用它

如果您坚持依靠
WebSecurity
来解析路由,您可以使用
RouteConstraint
,在实际请求该路由时将对其进行检查,这样您将有一个HTTP
Request
和经过身份验证/未经身份验证的用户

例如:

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;
    }
}
routes.MapRoute(
    name: "SomeRoute",
    url: "SomeRoute/{action}",
    defaults: new { controller = "MyCtrl", action = "Index" },
    constraints: new { CheckUserId = new CheckUserIdRouteConstraint() }
);
然后将约束附加到路线注册。例如:

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;
    }
}
routes.MapRoute(
    name: "SomeRoute",
    url: "SomeRoute/{action}",
    defaults: new { controller = "MyCtrl", action = "Index" },
    constraints: new { CheckUserId = new CheckUserIdRouteConstraint() }
);

请参阅

相关:它给您空值,因为ruteConfig类get execute in App_start事件是当第一个页面请求到达时触发一次的事件,其他事情是当时没有用户登录到系统。我使用了一个与
if(!WebSecurity.Initialized)对齐的断点
但当我开始调试程序时,它并没有停在这里。@Aikitchi,我在约束注册中犯了一个错误。正确的语法是
constraints:new{CheckUserId=new CheckUserIdRouteConstraint()}
。见修改后的答案。