我的 View 使用@Html.Action(…)
来反射(reflect)各种功能 block 。在打开页面时,站点会为在 Controller 方法中没有指向角色的用户显示授权对话框。 (例如“经理”或“来电者”)按“取消”得到:
401 - 未经授权:由于凭据无效,访问被拒绝。
如果用户没有必需的角色,@Html.Action 被忽略或什么都不显示,我是否可以改变我的应用程序行为?
我的看法:
@model InApp.ViewModel.ListViewModel
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div id="CallList">
@Html.Action("List","Call",new {id=Model.id})
</div>
<div class="Order">
@Html.Action("Create","Order",new {id=Model.id})
</div>
Controller :
[Authorize(Roles = "manager, caller")] //if a user is not 'manager' or 'caller'
public PartialViewResult List() // nothing is shown
{
//...private
return PartialView();
}
[Authorize(Roles = "manager, admin")]
public PartialViewResultCreate()
{
//...private
return PartialView();
}
试图找到正确的解决方案我发现了类似的问题:
Ignore @Html.Action() if user not in Role 和 asp.net MVC3 razor: display actionlink based on user role 但我不喜欢在我的 View 中使用“if”条件。我正在寻找一个复杂的解决方案来仅使用 AuthorizeAttribute 来隐藏和显示单独的部分,并避免在 View 或 Controller 中使用 if – else。感谢您的帮助!
最佳答案
我可以建议使用这个扩展方法:
这是 @Html.Action 的包装器,它通过反射检查用户权限。
public static MvcHtmlString ActionBaseRole(this HtmlHelper value, string actionName, string controllerName, object routeValues , IPrincipal user)
{
bool userHasRequeredRole = false;
Type t = Type.GetType((string.Format("MyProject.Controllers.{0}Controller",controllerName))); // MyProject.Controllers... replace on you namespace
MethodInfo method = t.GetMethod(actionName);
var attr = (method.GetCustomAttribute(typeof(AuthorizeAttribute), true) as AuthorizeAttribute);
if (attr != null)
{
string[] methodRequeredRoles = attr.Roles.Split(',');
userHasRequeredRole = methodRequeredRoles.Any(r => user.IsInRole(r.Trim())); // user roles check in depends on implementation authorization in you site
// In a simple version that might look like
}
else userHasRequeredRole = true; //method don't have Authorize Attribute
return userHasRequeredRole ? value.Action(actionName, controllerName, routeValues) : MvcHtmlString.Empty;
}
在 View 中使用:
@Html.ActionBaseRole("List","Call",new {id=Model.id},User)
关于c# - Asp.net MVC3 : is really based on roles @Html. Action (),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20303162/