janiv
janiv

Reputation: 749

Add ASP.NET Identity (User Management) to OData via Web API 2

I have an OData project that was created from Web API template (including credentials).

I have an ApplicationUser:IdentityUser class.

I have a TournamentContext : IdentityDbContext class.

I have the default AccountController that comes with the template with [RoutePrefix("api/Account")] attribute.

In WebApiConfig.cs For the web api template default routing I have

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new {id = RouteParameter.Optional});

For the OData support I've added:

config.Routes.MapODataRoute("odata", "odata", GetModel(),
            new DefaultODataBatchHandler(GlobalConfiguration.DefaultServer));

and

private static IEdmModel GetModel()
    {
        ODataConventionModelBuilder builder = new ODataConventionModelBuilder();            
        builder.EntitySet<Tournament>("Tournaments");
        return builder.GetEdmModel();
    }

Now, I want to expose the account/user management via the OData API. How do I achieve that?

Thanks, Janiv Ratson.

Upvotes: 3

Views: 1525

Answers (1)

Ivan Samygin
Ivan Samygin

Reputation: 4571

You can create ODataController for managing user identities using scaffolding:

1) right mouse click on Controllers folder, Add -> Controller...

2) choose "Web API 2 OData Controller with actions, Entity Framework"

3) in a dialog select generated model class for app users - ApplicationUser (WebApplication1.Models) by default - and appropriate data context

4) after generation is done you should replace DbSet property declaration automatically added to your data context

    public System.Data.Entity.DbSet<WebApplication1.Models.ApplicationUser> ApplicationUsers { get; set; }

with method declaration

    public DbSet<ApplicationUser> GetApplicationUsers()
    {
        return (DbSet<ApplicationUser>) Users;
    }

(because your data context is iherited from IdentityDbContext, which has IDbSet Users property). So there's error

Multiple object sets per type are not supported. The object sets 'ApplicationUsers' and 'Users' can both contain instances of type 'WebApplication1.Models.ApplicationUser'

unless you do the replacement.

5) last - you should replace in generated controller code "db.ApplicationUsers" to "db.GetApplicationUsers()".

Upvotes: 4

Related Questions