2013-04-22 11 views
7

Tôi sử dụng Siêu dữ liệu và JsonIgnore để loại bỏ trường đặc biệt khỏi việc tuần tự hóa.làm thế nào để động jsonignore theo người dùng ủy quyền?

[Authorize(Roles = "admin")] 
public class UserController : ApiController 
{ 
    public IEnumerable<user> Get() 
    { 
     using (var mydb = new ModelContainer()) 
     { 
      return mydb.userSet.ToList(); 
     } 
    } 
} 

[MetadataType(typeof(user_Metadata))] 
public partial class user 
{ 
    private class user_Metadata 
    { 
     [JsonIgnore] 
     public virtual password { get; set; } 

     public virtual adminFile { get; set; } 
    } 
} 

Làm cách nào để kiểm soát động trường nào sẽ được tuần tự hóa hay không. Đối với một số thứ như

public partial class user 
{ 
    private class user_Metadata 
    { 
     [JsonIgnore] 
     public virtual password { get; set; } 
     [Roes == admin?JsonIgnore:JsonNotIgnore] //some thing like this 
     public virtual adminFile { get; set; } 
    } 
} 

Trả lời

0

JsonIgnore là thuộc tính không thể được đặt động. Nhưng bạn có thể thử một cái gì đó tương tự như thế này.

public partial class user 
{ 
    private class user_Metadata 
    { 
     [JsonIgnore] 
     public virtual password { get; set; } 

     //[Roes == admin?JsonIgnore:JsonNotIgnore] //something like this 
     public virtual adminFile 
     { 
      get 
      { 
       if(Roes == admin) 
        return NULL; 
       else 
        return adminFile; 
      } 
      set 
      { 
       if(Roes == admin) 
        value = NULL; 
       else 
        value = adminFile; 
      } 
     } 

    } 
} 

Bằng cách này, bạn có thể lưu giá trị mặc định thay vì lưu giá trị thực tế cho thuộc tính.

+1

cảm ơn bạn, điều này có thể có được những điều để work.But Tôi muốn cách thức json.net như James nói –