我目前正在内部网上为我的实习工作(第一年comp。科学生) - 我拿了最后的实习生代码,不得不调试它/做一些调整。它到目前为止很棒;但我现在的工作是从Windows身份验证方法转变为基于表单的方法,而且我很遗憾。到目前为止,我已将Web.config中的身份验证模式更改为Forms,但问题是:
添加
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" /> <!-- Was in comments -->
</authentication>
<authorization>
<deny users="?" />
</authorization>
到我的Web.config,它将我重定向到需要我输入我的信息的基本登录页面。 (由于授权)
但它仍然显示Site.Master中的以下内容:
<div class="float-right">
Welcome <%: System.Environment.UserName %> - <a href='<%= Url.Action("MyProfile", "Employee") %>'>My Profile</a> | <%: Html.ActionLink("Logout", "Deco", "Home") %>
</div> <!-- Should only display if logged in -->
好像我还在登录,我可以更改我的个人资料。
只有在我的基于表单的身份验证登录时才能显示它吗?
编辑:此外,我该怎么做才能从Windows身份验证迁移。以形式为基础的?
EDIT2:这是我的AccountController的代码:
[Authorize]
[InitializeSimpleMembership]
public class AccountController : Controller
{
//
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
{
return RedirectToLocal(returnUrl);
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
WebSecurity.Logout();
//FormsAuthentication.SignOut();
return RedirectToAction("Index", "Home");
}
答案 0 :(得分:1)
我不确定您是否正在检查用户是否已登录应用以显示该段代码。如果没有,那么您可以先检查用户是否已登录,然后使用Request.IsAuthenticated
或User.Identity.IsAuthenticated
显示该html:
@if(Request.IsAuthenticated) {
<div class="float-right">
Welcome <%: System.Environment.UserName %> - <a href='<%= Url.Action("MyProfile", "Employee") %>'>My Profile</a> | <%: Html.ActionLink("Logout", "Deco", "Home") %>
</div> <!-- Should only display if logged in -->
}
或:
@if (User.Identity.IsAuthenticated) {
<div class="float-right">
Welcome <%: System.Environment.UserName %> - <a href='<%= Url.Action("MyProfile", "Employee") %>'>My Profile</a> | <%: Html.ActionLink("Logout", "Deco", "Home") %>
</div> <!-- Should only display if logged in -->
}
编辑:
您还应该更改登录方法,以使用FormsAuthentication.Authenticate
方法对用户进行身份验证:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && FormsAuthentication.Authenticate(model.UserName, model.Password, persistCookie: model.RememberMe))
{
return RedirectToLocal(returnUrl);
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
也在您的退出方法中使用FormsAuthentication.SignOut();