我在项目中创建了一个控制器。
[Authorize(Roles = "Admin")]
private StudentRepositor obj = new StudentRepositor();
public ActionResult Index()
{
var model = obj.GetStudentlist();
foreach (var stu in model)
{
stu.State = (stu.State == "1") ? "فعال" : "غیرفعال ";
}
return View(model);
}
我想检查控制器内部的权限,而不是在外面。
例如,有些事情是这样的:
public ActionResult Index()
{
if(Role=admin) return view2
if(role=teacher) return view1
}
我可以这样做吗?!!
祝你好运
答案 0 :(得分:6)
您应该可以使用User.IsInRole()
public ActionResult Index()
{
if(User.IsInRole("admin"))
{
//Return View
}
else if(User.IsInRole("teacher"))
{
//Return View
}
else
{
//Return View
}
}
答案 1 :(得分:0)
我建议您创建自定义授权属性,类似这样。
public class AuthorizationAttribute : FilterAttribute, IAuthorizationFilter
{
private readonly Type _userType;
public AuthorizationAttribute()
{
}
public AuthorizationAttribute(Type userType)
{
_userType = userType;
}
public void OnAuthorization(AuthorizationContext filterContext)
{
var currentHttpContext = filterContext.RequestContext.HttpContext;
if (!currentHttpContext.User.Identity.IsAuthenticated)
{
//Redirect
}
if (_userType != null)
{
var identity = filterContext.RequestContext.HttpContext.User.Identity.Name;
//Get type for identity
if(_userType != identityType)
{
//Redirect
}
}
}
}
之后你可以像这样使用它:
[Authorization(typeof(Admin))]
public ActionResult Create()
{}