哪里是验证用户在asp.net mvc中进行身份验证的最佳位置

ron*_*san 2 asp.net-mvc asp.net-mvc-3

我正在一个应用程序中工作,我需要验证该请求来自经过身份验证的用户.因为我基于用户Guid做了很多负载.

public ActionResult ManageEmployee()
{
      var loadedEmp = GetLoadedEmp(GetLoggedUserGuid());
      return View("Employee/Manage", loadedEmp);
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,我是否需要这样做"验证用户已通过身份验证"

public ActionResult ManageEmployee()
{
 if (!User.Identity.IsAuthenticated)
 {
        return View("Account/LogOn"); 
  }

  var loadedEmp = GetLoadedEmp(GetLoggedUserGuid());
  return View("Employee/Manage", loadedEmp);
}
Run Code Online (Sandbox Code Playgroud)

在每个ActionResult函数上,还是有一个野兽方法或集中解决方案.

谢谢

Jus*_*ner 11

使用AuthorizeAttribute控制器中的"操作"来要求用户登录以执行所述操作:

[Authorize]
public ActionResult ManageEmployee()
{
    // This code will only execute if the user is Authenticated
    var loadedEmp = GetLoadedEmp(GetLoggedUserGuid());
    return View("Employee/Manage", loadedEmp);
}
Run Code Online (Sandbox Code Playgroud)

使用该属性时,如果用户未登录,则会自动将用户重定向到登录页面(只要您的应用程序配置正确).


amu*_*rra 6

@Justin Niessner是对的,但如果你想要一个属性应用于控制器中的每个动作,你可以将AuthorizeAttribute放在类上:

[Authorize]
public class HomeController : AreaController { ... }
Run Code Online (Sandbox Code Playgroud)