我在控制器中有以下登录帖子操作:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
[Auditing]
public async Task<ActionResult> Login(LoginModel details, string returnUrl)
{
if (ModelState.IsValid)
{
AppUser user = await UserManager.FindAsync(details.Name,
details.Password);
if (user == null)
{
ModelState.AddModelError("", "Invalid name or password.");
}
else
{
ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,
DefaultAuthenticationTypes.ApplicationCookie);
ident.AddClaims(LocationClaimsProvider.GetClaims(ident));
ident.AddClaims(ClaimsRoles.CreateRolesFromClaims(ident));
AuthManager.SignOut();
AuthManager.SignIn(new AuthenticationProperties
{
IsPersistent = false
}, ident);
//Persist login into DB upon successful login
Loginrecord login = new Loginrecord();
login.Username = user.UserName;
login.SessionId = HttpContext.Session.SessionID;
Session["sessionid"] = HttpContext.Session.SessionID;
login.Date = DateTime.Now;
SQLLoginrecord sqlLogin = new SQLLoginrecord();
sqlLogin.PutOrPostLogin(login);
//End addition
return Redirect(returnUrl);
}
}
ViewBag.returnUrl = returnUrl;
return View(details);
}
由于从此操作成功登录可以转到任何需要授权的页面,用户在浏览器的地址栏中键入URL,如何显示指示登录成功的弹出消息?如果我使用ViewBag方法并添加Success变量,是否必须从需要身份验证的应用程序的每个View(包括一些没有共享布局)访问ViewBag?
答案 0 :(得分:0)
Redirect
方法将使用位置标头中的新网址向浏览器发出302响应,浏览器将为该网址发出全新的Http请求。所以ViewBag不会帮助你。
您可以考虑使用TempData
(适用于下次调用)将Login操作方法中的数据共享到任何其他操作方法。您可以编写一个动作过滤器来检查TempData项目并设置适当的ViewBag条目,以便您可以在其他视图中执行任何操作。
public class LoginMsg : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var msg=filterContext.Controller.TempData["LoginMsg"] as string;
if (!String.IsNullOrEmpty(msg))
{
filterContext.Controller.ViewBag.LoginMsg= msg;
}
base.OnActionExecuting(filterContext);
}
}
现在在您的Login类中,在重定向之前,设置TempData
public async Task<ActionResult> Login(LoginModel details, string returnUrl)
{
// do stuff
TempData["LoginMsg"]="Logged in successfully";
return Redirect(returnUrl);
}
现在使用我们的动作过滤器装饰你的其他动作方法(或者你可以在控制器级别上完成)。
[LoginMsg]
public ActionResult Dashboard()
{
return View();
}
在您的视图或_Layout中,您可以访问ViewBag项并调用代码来触发弹出控件。
<script>
var msg = "@ViewBag.Msg";
if (msg.length) {
// alert(msg);
// Call the code to fire the popup now
// yourMagicPopupPlugin.Popup(msg);
}
</script>