asp.net-mvc - ASP.NET MVC View - 显示基于授权的内容

标签 asp.net-mvc

很抱歉,如果您发现我在问愚蠢的问题。但我是 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/

相关文章:

c# - 使用 Quartz.NET 进行 MVC3 webapp 任务调度

c# - MVC3 在不需要时标记可为 null 的 bool

jquery - 有人有关于使用 MVC2 和 jQuery 进行客户端验证的好资源吗?

c# - 更正 JSON 结果对象

c# - 在 View 中使用 2 个模型时,此调用在以下方法或属性之间不明确 C# razor

c# - 当我尝试使用 Facebook 或 Google 登录时,GetExternalLoginInfoAsync 始终返回 null

asp.net-mvc - 具有键 'XXX' 的 ViewData 项的类型为 'System.String',但必须为 'IEnumerable<SelectListItem>' 类型

javascript - jQuery post 使用 ajax 来自可变数量的输入框

c# - 错误消息 "A potentially dangerous Request.Form value"

asp.net-mvc - Identity Server 4 将参数添加到登录页面