问题描述
|
如何将控制器类锁定为只能由一个或多个角色访问?我在第二个示例中尝试使用“ 0”,但它似乎强制要求授权,而不是授予对该页面的访问权限。
[PrincipalPermission(SercurityAction.?????????)]
public class MySecuredController { ...
要么
[Authorize(Roles=\"MyRoleName\")
public class MySecuredController { ...
要么
我完全错了吗?
整个脚本实际上只是MVC3教程...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Security.Permissions;
namespace mvc3test.Controllers
{
[Authorize(Roles=\"taxpayer\")]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = \"Welcome to ASP.NET MVC!\";
return View();
}
public ActionResult About()
{
return View();
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase dr405)
{
var saveLocation = Path.Combine(Server.MapPath(\"\\\\\"),\"returns\");
System.IO.Directory.CreateDirectory(saveLocation);
dr405.SaveAs(Path.Combine(saveLocation,User.Identity.Name) + \".xlsx\");
ViewBag.Message = String.Format(\"File name: {0},{1}Kb Uploaded Successfully.\",dr405.FileName,(int)dr405.ContentLength / 1024);
return View();
}
}
}
当我运行此程序时,该站点在输入我的凭据后使我登录。我知道这是因为我的名字出现在屏幕的右上角。但是,这只会使我一遍又一遍地进入登录屏幕。
更新资料
所以我在LogOn
动作的Redirect
方法中为User.IsInRole(\"taxpayer\")
的值添加了一个手表,其中User.Identity.Name
是有问题的用户名。 User.IsInRole(\"taxpayer\")
返回假。下面,当我运行aspnet_db存储的proc时,它指示返回列表中的用户.....
USE [aspnetdb]
GO
DECLARE @return_value int
EXEC @return_value = [dbo].[aspnet_UsersInRoles_GetUsersInRoles]
@ApplicationName = N\'/\',@RoleName = N\'taxpayer\'
SELECT \'Return Value\' = @return_value
GO
所以现在我想知道这是否是数据问题。有什么想法吗???
解决方法
如果访问页面的用户未经过身份验证或不是给定角色的成员(您的第二个选项是我使用的角色),则他们将被重定向到身份验证页面。这是一个过滤器,而不是授予。
,第二种方法
[Authorize(Roles=\"myrolename\")]
是正确的。如果用户没有该角色,则其行为是提示他们使用具有访问权限的角色登录。如果要更改该行为,则必须滚动自己的“授权”过滤器。