我见过很多例子,其中 html 元素的可见性可以在 cshtml 文件中使用类似的东西来切换:
if (User.IsInRole("Admin"))
{
<input type="button" value="Save" />
}
但是,是否有可能实现类似:
// User has update permission to User objects
User.HasPermission("User", "Update")
{
<input type="button" value="Save" />
}
我想在我的 MVC 应用程序中使用这两者,其中角色与许多权限相关联,并且权限也可以单独授予用户。
一种方法是覆盖 System.Security.Principal 和 System.Security.Identity,并在 Global.asax Application_AuthenticateRequest 方法集中:
object user = HttpContext.Current.Cache.Get(authTicket.Name);
MyIdentity identity = new MyIdentity((MyUser)user, true);
MyPrincipal principal = new MyPrincipal(identity);
Context.User = principal;
Thread.CurrentPrincipal = principal;
然后在 cshtml 文件中使用:
MyIdentity identity = (MyIdentity)User.Identity;
if (identity.User.HasClaim("User", "Update"))
{
<input type="button" value="Save" />
}
这种方法的问题是我必须在需要检查权限的任何地方都对 MyIdentity 进行强制转换。
有没有更好更有效的方法来做到这一点?我的目标是 MVC3 或 MVC4。
--
编辑:
根据 DavidG 的建议,我开始研究扩展方法。这就是我想出的:
public static class PrincipalExtensions
{
public static MyIdentity MyIdentity(this IPrincipal principal)
{
return principal.Identity as MyIdentity;
}
}
我该如何使用它?在一些示例中,我看到人们更改他们的 web.config - 尝试过 - 或干预控制器和 controllerFactory 以及 global.asax 代码。到目前为止,我还没有在我的 cshtml 文件中使用 MyIdentity。
--
编辑2:
更多进展:我在这里使用了说明:http ://rizzo7.blogspot.fi/2012/04/mvc-30-razor-custom-principal-and.html
得到它 - 有点 - 工作,现在我可以使用如下语法:
if (User.MyIdentity().User.HasClaim("User", "Update"))
{
<input type="button" value="Save" />
}
但是,在 Visual Studio 中,我收到一条错误消息:
System.Security.Principal.IPrincipal'不包含'MyIdentity'的定义,并且找不到接受'System.Security.Principal.IPrincipal'类型的第一个参数的扩展方法'MyIdentity'(您是否缺少 using 指令或装配参考?)
在我的视图的 Web.config 中,我有:
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="namespace.of.PrincipalExtensions"/>
</namespaces>
</pages>
尽管出现错误,该项目仍可正确编译和运行。每次可见性检查都会出错时,开发和调试会很痛苦。对此我能做些什么吗?
--
编辑-决赛!
谢谢大家,我会回答我自己的最后一个问题;只需要确保 cshtml 看到扩展类的命名空间。:)
我标记了 DavidG 的答案,因为它让我从正确的地方进行搜索,并给了我最需要的东西。谢谢!