Limit objects in a collection from User based serialization

I have a webapi that returns an object containing some collection of objects, which also contains a collection of objects. Each of these objects has a bool that represents if the object is "published." See the classes below for a general idea.

public class A { public int ID { get; set; } public List<B> b { get; set;} } public class B { public List<C> c { get; set; } public List<D> d { get; set; } public bool published { get; set; } } public class C { public string Title { get; set; } public bool published { get; set; } } public class D { public string Title { get; set; } public bool published { get; set; } } 

What is the best way to do this when I serialize any of these objects, if the unpublished child objects are not included, if the user does not meet the requirements, IE is not in a specific role. Can I add data attributes to my model in some way? I reviewed using custom IContractResolver , but I'm not sure if this is the best way to handle nested objects. Do I have to handle this at the serialization stage, or do I need to remove unpublished objects from children after I get the object from the database.

+6
source share
2 answers

As noted in the comments (fairly), I did it a little wrong.

I solved my problems if two requests for basic requests look something like this.

 A a = null; if(User.IsInRole("Role")){ a = db.A.Find(Id); } else { a = (from a in db.A join b in db.B on a.ID equals b.ID join c in db.C on b.ID equals c.ID join d in db.D on b.ID equals d.ID where a.ID == id && b.Published && c.Published && d.Published select a); } if(a == null) return NotFound(); return Ok(a); 

I tried to avoid such code, but I'm not sure if there is a better way to do this.

+1
source

In fact, I would suggest that some users download only the necessary data, as this will increase performance. The case when you want to download all the data (both published and unpublished) is trivial. For a user who can only view published items, I would make this request:

 A model = context.ACollection.Where(a => a.ID == id).Select(a => new A { ID = a.ID, b = abWhere(i => i.published == true).Select(i => new B{ published = true, c = icWhere(c_item => c_item.published == true), d = idWhere(d_item => d_item.published == true) }) }).Single(); 

This query should give you good performance.

+1
source

Source: https://habr.com/ru/post/970638/


All Articles