ASP.NET MVC5网站,在我创建它时没有任何身份验证,所以我没有任何内置的身份验证代码。
我现在添加了一个管理控制器,它将包含一些管理员的单个页面/操作(索引),并且还添加了一个LogIn操作...
public class AdminController : Controller {
[Authorize]
public ActionResult Index() {
// TODO - Add the admin stuff
return View();
}
#region LogIn
[HttpGet]
public ActionResult Login() {
return View();
}
[HttpPost]
public ActionResult Login(LoginViewModel livm) {
if (livm.UserName != "uid" || livm.Password != "pwd") {
ModelState.AddModelError("", "Your user name and password were not recognised. Please try again");
livm.Password = "";
return View(livm);
}
FormsAuthentication.RedirectFromLoginPage(livm.UserName, false);
return Content("OK", "text/text");
}
#endregion
}
注意我使用硬编码的用户名和密码进行测试。一旦它正常工作,我就会改变它!
LoginViewModel是一个简单的类,它具有用户名和密码的属性,以及一些有用的属性。
web.config文件包含以下内容......
<authentication mode="Forms">
<forms loginUrl="~/Admin/Login" />
</authentication>
...并且登录视图看起来像这样......
@using (Html.BeginForm("Login", "Admin", new {ViewBag.ReturnUrl}, FormMethod.Post, new {@class = "form-horizontal", role = "form"})) {
@Html.ValidationSummary(true)
<div class="form-group">
@Html.LabelFor(m => m.UserName, new {@class = "col-md-2 control-label"})
<div class="col-md-10">
@Html.TextBoxFor(m => m.UserName, new {@class = "form-control", title = "your user name"})
@Html.ValidationMessageFor(m => m.UserName)
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Password, new {@class = "col-md-2 control-label"})
<div class="col-md-10">
@Html.PasswordFor(m => m.Password, new {@class = "form-control", title = "Your password"})
@Html.ValidationMessageFor(m => m.Password)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input id="logInBtn" type="submit" value="Log in" class="btn btn-default" />
</div>
</div>
}
现在,如果您尝试访问/ Admin或/ Admin / Index,则会将您正确重定向到http://localhost:7154/Admin/Login?ReturnUrl=%2fAdmin%2fIndex,您可以在其中输入您的用户名和密码。
这里出错了。当您单击“登录”按钮时,您将被重定向到http://localhost:7154/default.aspx,这将提供404,因为该页面不存在。
如何将其重定向到请求的网址?在这种情况下,我不介意将重定向硬编码到/ Admin,因为它目前是唯一的安全页面,但我想知道如何重定向到用户请求的任何页面,如果我添加任何其他安全位。
答案 0 :(得分:1)
在表单定义中:
@using (Html.BeginForm("Login", "Admin", new {ViewBag.ReturnUrl}, FormMethod.Post, new {@class = "form-horizontal", role = "form"}))
您正在添加路线参数ReturnUrl
。为了使用它
在Login操作中添加其他参数:
[HttpPost]
public ActionResult Login(LoginViewModel livm, string returnUrl) {
if (livm.UserName != "uid" || livm.Password != "pwd") {
ModelState.AddModelError("", "Your user name and password were not recognised. Please try again");
livm.Password = "";
return View(livm);
}
FormsAuthentication.SetAuthCookie(livm.UserName, false);
//Assuming that user's login was successful simply redirect him to the requested url:
return this.RedirectToLocal(returnUrl);
}
private ActionResult RedirectToLocal(string returnUrl)
{
if (this.Url.IsLocalUrl(returnUrl))
{
return this.Redirect(returnUrl);
}
//Default redirect:
return this.RedirectToAction("Index", "Admin");
}