代码之家  ›  专栏  ›  技术社区  ›  Keith Nicholas

ASP。NET MVC帐户控制器使用指南?

  •  10
  • Keith Nicholas  · 技术社区  · 16 年前

    我正在查看MVC帐户控制器,它似乎来自ASP。NET Web窗体。关于如何使用它,有什么好的背景信息吗?

    您可以将其映射到用户数据库表,还是最好自己进行用户管理?

    如何在MVC中使用它来限制登录用户可以查看的页面?你必须自己完成这一切吗?

    网络上的哪些资源可以帮助理解ASP。NET成员资格?

    1 回复  |  直到 11 年前
        1
  •  18
  •   hangy    16 年前

    我正在查看MVC帐户 控制器。…它似乎来自 asp.net?

    Scott Guthrie在他的博客文章中很好地解释了这一点 ASP.NET MVC Preview 4 他基本上说MVC示例中的Account Controller使用ASP。NET成员资格提供程序,因此您可以使用其中任何一个。(我认为你可以在互联网上了解更多关于ASP.NET成员资格提供程序的信息。)如果你不想实现/使用其中之一,修改应用程序以使用你自己的用户管理可能是最好的选择。

    如何在MVC中使用它 限制登录用户的页面 可以查看吗?你必须全部滚动吗 那是你自己的事吗?

    您可以添加 Authorize 属性属于控制器类或动作方法。(相同 source 如上所述)

    // Only logged in users can access this controller.
    [Authorize]
    public class SomeController : Controller
    {
        #region Not really important for this example. :]
        // Maybe rather use a BLL service here instead of the repository from the DAL, but this example is already more verbose than required.
        private IStuffRepository stuffRepository;
    
        public SomeController(IStuffRepository stuffRepository)
        {
            if (null == stuffRepository)
            {
                throw new ArgumentNullException("stuffRepository");
            }
    
            this.stuffRepository = stuffRepository;
        }
        #endregion
    
        // The authorize attribute is inherited - only logged in users can use the index action.
        public ActionResult Index()
        {
            return View();
        }
    
        // Moderators can flag stuff.
        [Authorize(Roles="Moderator")]
        public ActionResult Flag(int id)
        {
            this.stuffRepository.Flag(id);
            return RedirectToAction("Index");
        }
    
        // Admins ans SysOps can delete stuff.
        [Authorize(Roles="Admin,SysOp")]
        public ActionResult Delete(int id)
        {
            this.stuffRepository.Delete(id);
            return RedirectToAction("Index");
        }
    
        // Only joed can change the objects stuff. ;)
        // (This is probably bullshit, of course, but I could not make any better example. I blame the fact it is late at night. :))
        [Authorize(Users="COMPANY\\joed")]
        public ActionResult ChangeId(int oldId, int newId)
        {
            this.stuffRepository.ChangeId(oldId, newId);
            return RedirectToAction("Index");
        }
    }