简体   繁体   English

ASP.NET MVC如何应用基于角色或基于身份验证的View呈现?

[英]ASP.NET MVC How to apply role-based or authentication-based View rendering?

i want to show/hide certain parts of a View based on Authentication-status or Roles. 我想根据身份验证状态或角色显示/隐藏视图的某些部分。 For my controller actions I have extended ActionFilterAttribute so I can attribute certain Actions. 对于我的控制器操作,我已经扩展了ActionFilterAttribute,因此我可以归因于某些操作。

<RequiresRole(Role:="Admin")> _
Function Action() as ActionResult
    Return View()
End Function

Is there a similar way (attributing) which I can use in the Views? 我可以在视图中使用类似的方法(归属)吗? (so not like this: (所以不喜欢这样: How can I create a view that has different displays according to the role the user is in? 如何根据用户所处的角色创建具有不同显示的视图? )

You can access the user's logged-in roles from the view like this: 您可以从视图中访问用户的登录角色,如下所示:

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

and maybe your extension method with something like: 也许你的扩展方法有:

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;" });
}

Obviously, I'm using JavaScript to perform an HTTP DELETE to my controller action, to prevent page crawlers from accidentally deleting data from getting my pages. 显然,我正在使用JavaScript对我的控制器操作执行HTTP DELETE,以防止页面抓取工具意外删除数据以获取我的页面。 In my case I'm extending JQuery with a delete() method to supplement the HTTP verb. 在我的例子中,我使用delete()方法扩展JQuery以补充HTTP动词。

I new this existed, but took a while to find. 我有新的存在,但需要一段时间才能找到。 Here's what I am using: 这是我正在使用的:

<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>

This allows you to show different content to different users based on their login state or credentials. 这允许您根据其登录状态或凭据向不同用户显示不同的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM