ASP.NET MVC账户控制器使用指南?

10

我正在查看MVC账户控制器,它似乎来自于ASP.NET WebForms。是否有关于如何使用它的良好背景信息?

您可以将其映射到用户数据库表中吗?还是最好自己编写用户管理?

在MVC中如何利用它限制已登录用户可以查看哪些页面?您必须自己制作所有这些吗?

哪些网络资源可以帮助理解ASP.NET Membership?

1个回答

18
我正在查看MVC账户控制器,它似乎来自asp.net?Scott Guthrie在他的关于ASP.NET MVC Preview 4的博客中对此有很好的解释。他基本上说MVC示例中的Account Controller使用了ASP.NET成员提供程序,因此您可以使用任何这些内容。(我认为您可以在互联网上找到有关ASP.NET成员提供程序的更多信息。)如果您不想实现/使用其中之一,则修改应用程序以使用自己的用户管理可能是最佳选择。
你如何在MVC中利用它来限制已登录用户可以查看的页面?你必须自己全部完成吗?您可以向控制器类或操作方法添加Authorize属性。 (与上述同一来源。)
// 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");
    }
}

很好的例子,依赖注入和非常棒的评论!+1 - Matt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接