How to structure a new ASP MVC app?

2020-03-04 07:55发布

问题:

I need to start a new mvc project and as always I have issues about asp identity, never know where to put it!

I plan to organize solution like this:

  • ProjectWebUI - mvc app with asp identity framework (made from internet template with authentication)
  • ProjectDataAccessLayer - with repository classes that use dapper as database access technology
  • ProjectWebAPI - web service

But I have a little confusion and before start coding I need advice from someone more experienced (as until now all my projects were just one project with data access in it):

  1. Is it good idea to have asp identity inside WebUI project that use standard Entity Framework for data access and use dapper for other data access in separate assembly?
  2. If asp identity is inside WebUI project will I have some issues to receive authenticated access to WebAPI project?

回答1:

That's how I organized one of my recent projects:

  • Common — this is a core project in the solution. It contains all the domain entities along with the ApplicationUser class that inherits from IdentityUser class from ASP.NET Identity Framework. Normally this class is found in a new ASP.NET MVC project template; I decided to put it into the core library because it represents a common entity that may be required for higher layers and levels of abstraction. Because of this, Common references Microsoft.AspNet.Identity.Core and Microsoft.AspNet.Identity.EntityFramework assemblies.

  • DataAccess — this project references Common library and contains Entity Franework DatabaseContext as well as some repositories. I use Code First approach and my DatabaseContext is inherited from IdentityDbContext<ApplicationUser>. So it gives me a nice database structure with tables for Users and Roles and other ASP.NET Identity stuff as well as tables that represent my custom business entities from the Common project, so I can easily connect my custom entities with Identity objects.

  • WebApi — this is a REST service that uses DataAccess and Common libraries. All the authorization and authentication job is done here using token authentication.

  • Web — this is just a web client for my REST service.

So, to answer your question: you can keep your ASP.NET Identity classes and Entity Framework database context inside a single project if it is really small and easy to manage; otherwise, it would be better to step away from the default project template and introduce layers for each major application module.