asp.net mvc - In MVC, how do I handle optional rendering of content in a view based on complex logic? -
i trying achieve authorization checks in view of more complex logic checking current role. want output parts users authorized it. want in view:
<p>everyone can read this</p> @if(complexauthorizationlogic()) { <p>only authorized can read this</p> }
the option can think of add properties model have in many places lots of code duplication doesn't feel right.
first of all, thinking problem in right way or should handle different? if not, recommend?
here's how accomplish this:
create helper/utility class, similar 1 below.
namespace your.root.namespace { public partial class securityprovider { public static bool hasanyrole(params string[] roles) { bool hasanyrole = false; if (isuserauthenticated()) { var user = httpcontext.current.user; var services = dependencyresolver.current.getservice<imembershipservice>(); hasanyrole = services.userhasanyrole(user.identity.name, roles); } return hasanyrole; } public static bool isuserauthenticated() { bool isauthenticated = false; var user = httpcontext.current.user; if (user != null && user.identity != null) { isauthenticated = httpcontext.current.user.identity.isauthenticated; } return isauthenticated; } } }
then use relevant method in view.
@if(securityprovider.hasanyrole("admin")) { <div> classified content! must admin see this! </div> }
you can find entire class in sample project made.
Comments
Post a Comment