SHARE
TWEET

Untitled

a guest Jul 17th, 2017 48 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public class JsonPermissionBasedFormatter : PartialJsonMediaTypeFormatter
  2.     {
  3.         public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType)
  4.         {
  5.             User user = request.GetOwinContext()?.Request.Get<User>("AuthorizationFilter:CurrentUser");
  6.             var formatter = (PartialJsonMediaTypeFormatter)base.GetPerRequestFormatterInstance(type, request, mediaType);
  7.              formatter.SerializerSettings = SerializerSettings;
  8.             formatter.SerializerSettings.ContractResolver = new PermissionBasedContractResolver(user);
  9.             return formatter;
  10.         }
  11.     }
  12.    
  13. public PermissionBasedContractResolver(User user)
  14.     {
  15.         _user = user;
  16.         NamingStrategy = new CamelCaseNamingStrategy
  17.         {
  18.             ProcessDictionaryKeys = true,
  19.             OverrideSpecifiedNames = true
  20.         };
  21.     }
  22.  
  23.     protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
  24.     {
  25.         if (member == null)
  26.         {
  27.             throw new ArgumentNullException(nameof(member));
  28.         }
  29.         JsonProperty property = base.CreateProperty(member, memberSerialization);
  30.  
  31.         var propertyInfo = member as PropertyInfo;
  32.         if (propertyInfo != null)
  33.         {
  34.             if (!PermissionsHelper.IsPropertyVisibleForUser(propertyInfo, _user))
  35.             {
  36.                 property.ShouldSerialize = DoNotSerialize;
  37.             }
  38.         }
  39.         return property;
  40.     }
  41.  
  42.     static bool DoNotSerialize(object o)
  43.     {
  44.         return false;
  45.     }
  46. }
  47.    
  48. Parallel.For(1, 10000, _ =>
  49.             {
  50.                 Get(ordinaryUser, isAdmin: false);
  51.                 Get(adminUser, isAdmin: true);
  52.             });
RAW Paste Data
Top