ASP MVC Make Class Namespace Available In All Views

699 Views Asked by At

I have the following Permission class. How can I make this available in all views without having to use the following using statement in each view @using MyApp.Extensions

using System.Security.Principal;

namespace MyApp.Entensions
{
     public class Permissions
     {
         private readonly IPrincipal user;

         public Permissions(IPrincipal user)
         {
             this.user = user;
         }


         public bool CanEditItems
         {
            get { return user.IsInAnyRole("Manager", "Admin"); }
         }

        public bool CanDeleteItems
        {
           get { return user.IsInAnyRole("Admin"); }
        }

        // Other permissions

     }
 }

I've tried adding it to the views web.config as follows but I don't get any intellisense when tryin to call something like @if (User.CanDeleteItems)

<pages pageBaseType="System.Web.Mvc.WebViewPage">
  <namespaces>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Optimization"/>
    <add namespace="System.Web.Routing" />
    <add namespace="MyApp.Extensions" />
 </namespaces>
</pages>
1

There are 1 best solutions below

1
Peter Morris On BEST ANSWER

If you want to add extensions to IPrinciple then you need an extension class, like so

using System.Security.Principal;

namespace MyApp.Entensions
{
     public static class Permissions
     {
         public static bool CanEditItems(this IPrinciple user)
         {
            return user.IsInAnyRole("Manager", "Admin"); 
         }

        public static bool CanDeleteItems(this IPrinciple user)
        {
           return user.IsInAnyRole("Admin"); 
        }

        // Other permissions

     }
 }

Not that the class is public + static, and the extension methods are public + static and also have "this" before the first parameter. You will need to change your view to use CanEditItems() as a method instead of a property.

if (System.Web.HttpContext.Current.User.CanEditItems()) { ... }