I'm working with a WebApi project in C# (EF code first) and I'm using OData. I have a "User" model with Id, Name, LastName, Email, and Password.
In controller for example I have this code:
// GET: odata/Users
[EnableQuery]
public IQueryable<User> GetUsers()
{
return db.Users;
}
If I call /odata/Users I'll get all the data: Id, Name, LastName, Email, and Password.
How can I exclude Password from results but keep available in controller to make Linq queries?
I made a craft and temporary solution to this problem (is not the best solution because UserInfo is not an entity type and not support $select or $expand). I created a new model called UserInfo just with the properties I need (apart of User):
public class UserInfo
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
Then I changed the method in the controller:
// GET: odata/Users
[EnableQuery]
public IQueryable<UserInfo> GetUsers()
{
List<UserInfo> lstUserInfo = new List<UserInfo>();
foreach(User usr in db.Users)
{
UserInfo userInfo = new UserInfo();
userInfo.Id = usr.Id;
userInfo.Name = usr.Name;
userInfo.Email = usr.Email;
lstUserInfo.Add(userInfo);
}
return lstUserInfo.AsQueryable();
}
I'm a little late to the topic but I think this might help you out.
I assume that you will want to encrypt the password for storage purposes. Have you looked at using an odata action to set the password? Using an action lets you ignore the password property when setting up your entities while still exposing a clean way to the end user to update the password.
first: ignore the password property
builder.EntitySet<UserInfo>("UserInfo").EntityType.Ignore(ui => ui.Password);
second: add your odata action
builder.EntityType<UserInfo>().Action("SetPassword").Returns<IHttpActionResult>();
Then add the SetPassword method to your UserInfoController.