【发布时间】:2019-02-01 18:22:10
【问题描述】:
我正在使用 ASP.Net MVC 开发一个简单的基于自定义角色的 Web 应用程序,在我的登录操作中,我正在创建一个 Profile 会话,如下所示:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
using (HostingEnvironment.Impersonate())
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
var employeeProfile = AccountBal.Instance.GetEmployee(loginId);
Session["Profile"] = employeeProfile;
FormsAuthentication.SetAuthCookie(model.UserName, true);
}
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", @"The user name or password provided is incorrect.");
return View(model);
}
}
我正在检查这个或在所有控制器操作中使用这个会话,如下所示:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateOrEdit(MyModel model)
{
var employee = (Employee) Session["Profile"];
if (employee == null)
return RedirectToAction("Login", "Account");
if (ModelState.IsValid)
{
// Functionality goes here....
}
}
有什么方法可以将这段会话检查代码移动到基类或集中类中?因此,我不需要每次都在 Controller Actions 中检查它,而是直接访问属性
说,
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateOrEdit(MyModel model)
{
var employee = _profileBase.GetCurrentProfile();
if (employee == null)
return RedirectToAction("Login", "Account");
if (ModelState.IsValid)
{
// Functionality goes here....
}
}
【问题讨论】:
-
使用
BaseController继承您的控制器,并在该控制器中写入方法GetCurrentProfile()并在其中添加您的会话代码GetCurrentProfile,并在您想要的控制器中使用此方法,如var employee = GetCurrentProfile();
标签: asp.net-mvc session model-view-controller base-class