Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 876
Martín Avatar asked Jan 05 '15 14:01

Martín


Video Answer


1 Answers

How can I exclude Password from results but keep available in controller to make Linq queries?

Ignore it. From Security Guidance for ASP.NET Web API 2 OData:

There are two ways to exlude a property from the EDM. You can set the [IgnoreDataMember] attribute on the property in the model class:

public class Employee
{
    public string Name { get; set; }
    public string Title { get; set; }
    [IgnoreDataMember]
    public decimal Salary { get; set; } // Not visible in the EDM
}

You can also remove the property from the EDM programmatically:

var employees = modelBuilder.EntitySet<Employee>("Employees");
employees.EntityType.Ignore(emp => emp.Salary);
like image 115
ta.speot.is Avatar answered Sep 20 '22 16:09

ta.speot.is