如果在asp.net mvc中的另一个视图失败,则重定向授权属性

时间:2014-02-19 19:10:17

标签: asp.net-mvc authorize-attribute

所以我对[Authorize]标记有疑问。我需要用户具有admin的角色才能访问某个视图。它工作得很好,只允许“管理员”转到它而不是“用户”。但是每当用户访问它时,都会给我这个:

Server Error in '/' Application.

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly. 

Requested URL: /Login.cshtml

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34009 

所以我的问题是,当用户访问时如何将其重定向到另一个视图?

所以这是我的索引控制器:

[Authorize(Users = "Admin")]
        public ActionResult Index()
        {
            var user = db.User.Include(u => u.UserRole);
            return View(user.ToList());
        }

1 个答案:

答案 0 :(得分:1)

您可以通过两种方式解决此问题:

  1. 让匿名用户可以访问索引操作,并根据角色调用不同的函数。
  2. 创建您自己的自定义授权属性(您可以找到示例here)。
  3. 两种方法都很好,没有明显的优势/劣势,所以你可以选择其中任何一种。

    希望这有帮助。