我正在开发一个asp.net MVC 4应用程序,我有一个局部视图,它在bootstrap模式弹出窗口中打开。这个局部视图有一个这样的表单标签:
@using (Html.BeginForm("Reserve", "Home", FormMethod.Post, new { Id = "frmMakeReservation" }))
{
}
我有一个名为Reserve with Authorize属性的动作方法,如下所示:
[Authorize(Roles = "Customer")]
[POST("Reserve")]
public ActionResult Reserve(My model model)
{
}
当用户点击弹出窗口上的提交按钮时,Control转到帐户/登录,当用户输入凭据时,会调用以下方法:
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
并且在If条件中我得到404错误/ Reserve不存在,即使我有Reserve视图。我想在登录后,它需要具有Get属性的动作方法。但我需要Post action方法来获取Reserve action方法
中的popup值第二个问题是即使我使用[Authorize(Roles =“Customer”)]属性,但如果具有其他角色的用户输入登录信息,我可以获得登录成功。
请建议解决方案。
答案 0 :(得分:0)
通常你需要设置登录控制器并重定向到你想要的页面,如果成功的那样:
[HttpPost]
[AllowAnonymous]
public ActionResult Login(LoginDto login)
{
string roles = "customers, Admin"; // this is the roles that you will add into roles authentications
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
userId, //user id
DateTime.Now,
DateTime.Now.AddMinutes(20), // expiry
false, //do not remember
roles,
"/");
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(authTicket));
Response.Cookies.Add(cookie);
return RedirectToAction("Reserve", "MyController")
}
然后您需要在身份验证发生时将这些角色输入到主体中(在Global.Asax文件中):
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity is FormsIdentity)
{
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = (id.Ticket);
if (!string.IsNullOrEmpty(ticket.UserData))
{
string userData = ticket.UserData;
string[] roles = userData.Split(',');
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, roles);
}
}
}
}
}
然后您可以在方法中使用授权属性,例如代码:
[Authorize(Roles = "Customer")]
[HttpPost]
public ActionResult Reserve(My model model)
{
}