ASP.NET MVC役割ベースまたは認証ベースのビューレンダリングを適用する方法
-
03-07-2019 - |
質問
i認証ステータスまたはロールに基づいてビューの特定の部分を表示/非表示にしたい。コントローラーアクションについては、ActionFilterAttributeを拡張して、特定のアクションを属性付けできるようにしました。
<RequiresRole(Role:="Admin")> _
Function Action() as ActionResult
Return View()
End Function
ビューで使用できる同様の方法(属性)はありますか? (このようにしないでください: ユーザーの役割に応じて異なる表示を持つビューを作成するにはどうすればよいですか)
解決
次のようなビューから、ユーザーのログインロールにアクセスできます。
<% 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を実行し、ページクローラーが誤ってデータを削除してページを取得しないようにします。私の場合は、HTTP動詞を補足するdelete()メソッドでJQueryを拡張しています。
他のヒント
これは存在していましたが、見つけるのに時間がかかりました。私が使用しているものは次のとおりです。
<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>
これにより、ログイン状態または資格情報に基づいて異なるユーザーに異なるコンテンツを表示できます。
所属していません StackOverflow