用户在控制器中为 Null 但在视图中具有值
User is Null in controller but in View has Value
我对 Authentication
使用 ASP.NET MVC 5
和 Identity
,我的问题是下面的代码:
User.Identity.IsAuthenticated
User
是 Null ,但我在 View Like belowe 中使用了 Above 代码,它的工作正常并且用户有 Value 。
@if (User.Identity.IsAuthenticated)
{...}
什么是物质?
为了做到这一点,我在 google 上搜索并找到了
的方法
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
}
我怀疑您正试图在控制器的构造函数中调用此方法。此构造函数在 HTTP 请求执行管道中调用得太早,并且 HttpContext 在那里不可用。您可以在 Initialize 方法中访问 HttpContext:
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
// Now you can access the HttpContext and User
if (User.Identity.IsAuthenticated)
{
...
}
}
我对 Authentication
使用 ASP.NET MVC 5
和 Identity
,我的问题是下面的代码:
User.Identity.IsAuthenticated
User
是 Null ,但我在 View Like belowe 中使用了 Above 代码,它的工作正常并且用户有 Value 。
@if (User.Identity.IsAuthenticated)
{...}
什么是物质?
为了做到这一点,我在 google 上搜索并找到了
的方法protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
}
我怀疑您正试图在控制器的构造函数中调用此方法。此构造函数在 HTTP 请求执行管道中调用得太早,并且 HttpContext 在那里不可用。您可以在 Initialize 方法中访问 HttpContext:
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
// Now you can access the HttpContext and User
if (User.Identity.IsAuthenticated)
{
...
}
}