Check User.Identity.IsAuthenticated in ActionFilter immediately after logging in

I mainly use AccountController from ASP.NET MVC samples. It uses FormsAuthentication to handle user login. To be sure, here is the code to process the user login:

    public ActionResult LogOn(string userName, string password, bool rememberMe, string returnUrl)
    {
      if (!ValidateLogOn(userName, password))
      {
        return View();
      }

      FormsAuth.SignIn(userName, rememberMe);


      //Session["userId"] = 1;


      if (!String.IsNullOrEmpty(returnUrl))
      {
        return Redirect(returnUrl);
      }
      else
      {
        return RedirectToAction("Index", "Home");
      }
    }

As you can see from the commented line, I would like to set the Session variable in this method. However, I decided that this is not the most elegant way to set the Session variable directly in the controller. It is also inconvenient when the module tests this method (although I could mock him, of course, but still).

, , ActionFilterAttribute, . , . :

  public class SetSessionAttribute : ActionFilterAttribute
  {
    public override void OnResultExecuted(ResultExecutedContext resultContext)
    {      
      if (resultContext.HttpContext.User.Identity.IsAuthenticated)
      {
        resultContext.HttpContext.Session["userId"] = 1;
      }

      base.OnResultExecuted(resultContext);
    }
  }

, User.Identity.IsAuthenticated false " ". OnResultExecuted, , , , , . OnActionExecuting, OnActionExecuted OnResultExecuting, false.

? ?

+3
1

, User.Identity.IsAuthenticated , , .

, Session ViewData routeValues.

0

Source: https://habr.com/ru/post/1710770/


All Articles