Two step authentication in MVC?

放肆的年华 提交于 2019-12-06 11:12:53

You can do what you want in MVC by leveraging RedirectToRouteResult and a custom cache updating ActionFilter. This is called the PRG (Post-Redirect-Get) pattern. You are actually already doing this, but it gets a little confused, because what you are doing is a cross between the classic ASP.NET way of doing things and the MVC way of doing things. There's nothing wrong with your initial approach (provided it is working correctly), but to do the same sort of thing and have more control and understanding of how it works in the scheme of things you could do something like:

public class AuthenticationController :Controller
{
    [HttpPost]
    public RedirectToRouteResult Login(string username, string password)
    {
        //authenticate user
        //store authentication info in TempData like
        bool authenticated = true|false; // do your testing
        if(authenticated)
        {
            TempData["MustUpdateCache"] = true | false;
            return RedirectToAction("LoginSuccess", new{userId = membershipUser.UserId});                
        }
        else
        {
            TempData["MustUpdateCache"] = true | false;
            return RedirectToAction("Login");
        }
    }

    [HttpGet, UpdateCache]
    public ActionResult LoginSuccess(Guid userId, string url)
    {
        HttpContext.User = LoadUser(userId);
        return View();
    }

    [HttpGet, UpdateCache]
    public ViewResult Login()
    {
        return View();
    }

}
public class UpdateCacheAttribute:ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        var tempData = filterContext.Controller.TempData;
        if (tempData.ContainsKey("MustUpdateCache") && (bool)tempData["MustUpdateCache"])
        {
            UpdateCache(filterContext);
        }
    }

    void UpdateCache(ControllerContext controllerContext)
    {
        //update your cache here
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!