首页 > Controller.Request.IsAuthenticated与Controller.User是什么时候被赋值的?

Controller.Request.IsAuthenticated与Controller.User是什么时候被赋值的?

Controller.Request.IsAuthenticated与Controller.User是什么时候被赋值的?

Request.IsAuthenticated;
User.Identity.IsAuthenticated;
User.Identity.Name;

在用的时候 MVC的 _LoginPartial.cshtml文件中


@using Microsoft.AspNet.Identity
@if (Request.IsAuthenticated)
{
    using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
    {
    @Html.AntiForgeryToken()

    <ul class="nav navbar-nav navbar-right">
        <li>
            @Html.ActionLink("你好," + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
        </li>
        <li><a href="javascript:document.getElementById('logoutForm').submit()">注销</a></li>
    </ul>
    }
}

这个 Request.IsAuthenticated 是在什么时候被赋值的,在编写代码时如何介入,我看了一点反编译的代码,不太能看懂而且只能Get 不能Set?

因为我想自己来写用户登录控制,但是希望用上Request.IsAuthenticated 和User这样就不用每次验证Session。

还有Controller.User。如何使用这个。什么时候能赋值?

望大神解答,谢谢!


这一切发生在 Middleware 之中。请参考此例子:
https://github.com/aspnet/Security/tree/dev/samples/CookieSample

其验证的核心代码是:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AutomaticAuthenticate = true
});

这将启用Cookie验证的Middleware,将它放在app.UseMvc方法之前,这样Cookie验证Middleware将在请求传递到Mvc之前进行登录校验。

进行登录的核心在以下2句代码:

var user = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "bob") }, CookieAuthenticationDefaults.AuthenticationScheme));
await context.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, user);
【热门文章】
【热门文章】