Exclude property from WebApi OData (EF) response in c#

asp.net-web-api c# entity-framework linq odata

Question

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?

1
9
1/5/2015 2:45:14 PM

Accepted Answer

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();
}
0
1/5/2015 4:18:55 PM

Popular Answer

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow