很抱歉,如果您发现我在问愚蠢的问题。但我是 ASP.NET 的新手,我遇到了一个问题:
我正在写一个简单的博客来学习asp.mvc,如果用户登录,我想在博客标题旁边显示一个编辑链接。目前我必须将 currentUser 对象添加到 Model 并检查 IsLogged属性来决定是否应该显示编辑链接。问题是,如果没有登录用户,我必须创建一个假的 currentUser 来插入到其他模型中才能使其工作。问题是还有其他优雅的方式来做到这一点。例如,我们可以在 Controller 中使用 [Authorize] 属性来允许或不允许访问某个 Action。还有类似的方式申请View吗?
最佳答案
如果您使用表单例份验证,则此属性已存在于 Request 对象中:
Request.IsAuthenticated
在您看来,您可以通过执行以下操作来解决问题:
<% if(this.Request.IsAuthenticated)
{
%>
<%= Html.ActionLink("Edit", url - to - action) %>
<% }
%>
但我认为您真正的问题是检查当前用户是否可以编辑当前博客。 在这种情况下,您可以在 ViewPage 对象上执行扩展方法 CanEdit :
<% if(this.CanEdit(this.User))
{
%>
<%= Html.ActionLink("Edit", url - to - action) %>
<% }
%>
扩展看起来像这样:
public static class ViewExtensions
{
public static bool CanEdit(ViewPage view, MyUser user)
{
bool retour = false;
if(principal != null)
{
// get your blog from the view
Blog blog = view.ViewData["myBlog"];
// check if the principal is the owner
retour = (blog.Owner.Id == user.Id);
}
return retour;
}
}
关于asp.net-mvc - ASP.NET MVC View - 显示基于授权的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/685186/