c# - MVC 5 Identity 2.0 在登录时显示配置文件完成情况

标签 c# asp.net-mvc-5 asp.net-identity

使用 MVC 5 和 Identity 2.0,我向 ApplicationUserClass 添加自定义属性,例如 FirstNameLastNameAddress 。这些将是数据库中的新字段。当用户注册应用程序时,他/她将仅输入电子邮件地址和密码。他们注册并登录后,我想强制他们完成个人资料,或者至少每次登录时,他们都应该被重定向到个人资料完成页面,在那里他们可以提及名字、姓氏和地址。完成个人资料后,他们每次登录时都不会被重定向到完整个人资料页面。

类似于:

if UserProfile != Completed

   go to CompleteProfilePage

else

   go to MainPage

最佳答案

您可以尝试全局过滤器。这将不允许您的用户通过手动修改 URL 来绕过检查。

public class ProfileCompletionCheckAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        //this will prevent redirect for still unauthenticated users
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            return;

        //replace these to actual values of your profile completion action and controller
        string actionOfProfilePage = "Index";
        string controlerOfProfilePage = "Home";

        bool areWeAlreadyInProfilePage = filterContext.ActionDescriptor.ActionName == actionOfProfilePage
            && filterContext.ActionDescriptor.ControllerDescriptor.ControllerName == controlerOfProfilePage;

        if (areWeAlreadyInProfilePage) //this will prevent redirect loop
            return;

        bool isProfileComplete = false; //replace this with your custom logic

        if (!isProfileComplete)
        {                
            filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary 
                { 
                    { "controller", controlerOfProfilePage }, 
                    { "action", actionOfProfilePage } 
                });
        }
    }
}

要启用它,只需将其添加到 FilterConfig.cs

filters.Add(new ProfileCompletionCheckAttribute());

关于c# - MVC 5 Identity 2.0 在登录时显示配置文件完成情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23720394/

相关文章:

c# - 使用 ScrollViewer.ScrollToEnd() 执行 AutoScroll 仅在调试时有效,事件处理程序太简单

javascript - 当我使用 angularjs 从 MVC Controller 获取数据时,OwlCarousel 不工作

c# - 从外部项目连接到现有 MVC 5 数据库(身份模型)

asp.net-mvc - ASP.NET身份登录

C#重构这段乱七八糟的代码!

c# - 如何找出未调用 C# .NET 程序集中的哪些代码

c# - 获取用户角色的最快方法

c# - 无法保存对身份用户的更改?

asp.net-mvc - 与Microsoft.AspNet.Identity的自定义成员身份-CreateLocalUser失败

c# - 覆盖抽象类的属性?