ASP.NET MVC如何应用基于角色或身份验证的视图渲染?

6
我希望你能根据身份验证状态或角色,显示/隐藏视图的特定部分。对于我的控制器动作,我已经扩展了ActionFilterAttribute,以便可以注释某些操作。
<RequiresRole(Role:="Admin")> _
Function Action() as ActionResult
    Return View()
End Function

在视图中,是否有一种类似的方式(归属),我可以使用它?(不像这样:如何创建一个根据用户角色具有不同显示的视图?


1
你为什么要创建一个ActionFilterAttribute?Authorize属性可以接受一个Roles参数。 - Çağdaş Tekin
没错 :-) 我创建了自己的只是为了学习。 - Ropstah
2个回答

6
您可以通过以下方式从视图中访问用户已登录的角色:

<% if (Page.User.IsInRole("Admin")) { %>
        <td>
          <%= Html.DeleteButton("delete", model.ID) %>
        </td>
<% } %>

也许你可以使用类似以下的扩展方法来实现此功能:
public static string DeleteButton(this HtmlHelper html, 
    string linkText, int id)
{
    return html.RouteLink(linkText,
     new { ID = id, action = "Delete" },
     new { onclick = "$.delete(this.href, deleteCompleted()); return false;" });
}

显然,我正在使用JavaScript执行HTTP DELETE到我的控制器操作,以防止页面爬虫意外删除数据并获取我的页面。在我的情况下,我正在扩展JQuery的delete()方法来补充HTTP动词。


好的,使用基于属性的视图渲染可能不太可能。我应该使用 If 语句... 谢谢 - Ropstah

0

我知道这个东西存在,但是找了一段时间才找到。这是我正在使用的:

<asp:LoginView runat="server">
    <AnonymousTemplate>
        You are not logged in yet. Please log in.
    </AnonymousTemplate>
    <RoleGroups>
        <asp:RoleGroup Roles="Admin">
            <ContentTemplate>
                You are an Admin.
            </ContentTemplate>
        </asp:RoleGroup>
        <asp:RoleGroup Roles="Customers">
            <ContentTemplate>
                You are a customer.
            </ContentTemplate>
        </asp:RoleGroup>
    </RoleGroups>
    <LoggedInTemplate>
        Simple Log in check
    </LoggedInTemplate>
</asp:LoginView>

这使您能够根据用户的登录状态或凭据显示不同的内容。


这是WebForms。我相信原帖是关于MVC的。 - Ethan Schofer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接