RedirectToAction
从另一个动作调用控制器动作时是否需要使用?我目前只是直接调用它们,因为我不希望它们返回,因此我绕过 Authorize 标记到我的一个操作(它执行我想要的操作)。
您能否让我知道这是否是错误的形式,如果是,我应该创建多个新操作来设置客户端 cookie 还是直接在LogOn()
操作中设置它们?
我可以改为SwitchClient
私有,然后公开授权操作,仅供客户端管理员使用吗?然后,将通过该操作调用私有操作LogOn
,但除非用户通过管理员身份验证,否则无法访问该操作。
这是我的代码:
[HttpGet]
[CustomAuthorizeAccess(Roles = "Administrator", RedirectResultUrl = "Unauthorized")]
public ActionResult SwitchClient(string client)
{
if (Request.Cookies["Client"] == null)
{
HttpCookie clientCookie = new HttpCookie("Client", client);
Response.Cookies.Add(clientCookie);
}
else
{
Response.Cookies["Client"].Value = client;
}
return new RedirectResult(Request.UrlReferrer.AbsolutePath);
}
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (MembershipService.ValidateUser(model.UserName, model.Password))
{
FormsService.SignIn(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
//Add user's role to cookies (assumes each user only has one role)
string role = Roles.GetRolesForUser(model.UserName).First();
HttpCookie roleCookie = new HttpCookie("Role", role);
if (role == "client1")
{
SwitchClient("client1");
}
else if (role == "client2")
{
SwitchClient("client2");
}
else if (role == "Administrator" || role == "client3")
{
SwitchClient("client3");
}
//Make role cookie persistent for 7 days
//if user selected "Remember Me"
if (model.RememberMe)
{
roleCookie.Expires = DateTime.Today.AddDays(7);
}
if (Response.Cookies["Role"] != null)
{
Response.Cookies["Role"].Value = null;
Response.Cookies.Remove("Role");
}
Response.Cookies.Add(roleCookie);
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}