asp.net-web-api-odata

How to restrict access to some properties or classes in ASP.NET Web API OData?


I have class:

public class Person
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual DateTime BirthDate { get; set; }
}

And I have WebAPI OData Controller:

public class PeopleController : ODataController
{
    [Queryable]
    [HttpGet]
    public IQueryable<Person> Get()
    {
        return (new MyEfContext()).People;
    }
}

Also I have in global.asax the next code:

ODataConventionModelBuilder modelBuilder = new ODataConventionModelBuilder();
modelBuilder.EntitySet<Person>("Person");
config.Routes.MapODataRoute(
            routeName: "MainModelQueryOdata",
            routePrefix: "query/main",
            model: modelBuilder.GetEdmModel(),
            pathHandler: new DefaultODataPathHandler(),
            batchHandler: new DefaultODataBatchHandler(GlobalConfiguration.DefaultServer),
            routingConventions: conventions);

I want to hide property BirthDate from non-administrators and when current user is not that Person. How to better achieve it in ASP.NET WebAPI OData? I have CurrentUserId to compare with person.Id and I have CurrentUserIsAdmin flag to check. The problem is that I cannot add condition to Odata Model through modelBuilder as there is not support for such behavior - I can only completely remove entity or property for everybody, but I need to show it to Administrators and people themselfes.


Solution

  • I think Dynamic Model is what you need.

    Check this sample code: https://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/OData/v4/DynamicEdmModelCreation/ReadMe.txt