I am new to MVC and Web API. I created two separate projects. One ASP.NET MVC 5 (MyUI) and other ASP.NET Web API 2 (MyApi). I would like to keep my API project separate from my UI layer.
The AccountController class in MVC project (MyUI) is essentially doing the same that the AccountController in the API project does (MyApi). I first thought about making the MyUI.AccountController a sub class of MyApi.AccountController but then I quickly realize that first inherits from Controller and second from ApiController type.
So my questions are:
In order to remove data access logic from MVC 5 project, should I
just convert the AccountController to a wrapper class which will
essentially call the corresponding methods from the
MyApi.AccountController?
Is there a better approach?
Edit:
Edit 2:
While trying to articulate the problem I realized that I was going about it incorrectly. My confusion came from the ASP.NET Identity implementations which were embedded within the API project. That needs to be moved to the Data Access layer and both controllers need to access them the same way which is a whole different can of worms :)
Thanks!!
Method 1 seems a plausible solution but what I would suggest is to create a new class library and there put your data logic. In that way, the MVC project and the Web Api project could connect to that class library.
The reason is that you never know if you write another UI layer, Service layer or other connectivity layer. All those layers could then connect to the same data logic layer.
Extract the common implementation into a separate project (a class library for instance). Your business logic must be the same no matter how you access it. After all, the web service and the site are only a view of the same information and the same control logic. In the future you might be required to write a fat client in WPF or a service in WCF and you do not want to rewrite everything, do you?
I think you are asking about layering application. basically the choice depends on requirements.If you are following data centric design check this layering
Research about DI,ORM,Repository Pattern, SOLID Principlese
Related
Solution Structure:
MyProject - WEBAPI
MyProject.CORE - Class Library
MyProject.Models - Class Library
MyProject.DAL - Class Library
Project References:
MyProject refers to CORE , MODELS
MyProject.CORE refers to DAL,MODELS
MyProject.DAL refers to MODELS
Project Description:
I am trying to create an application with ASP.NET MVC WEB API . so that I can call my API in future mobile applications. My idea behind this layered architecture is WEB API project will hold the front end views of my desktop application and call's the API controller methods on button click events . The event handler methods in API controller will call the Methods in the CORE project where I will implement the business logic.Then the call will be going to DAL where I will call the DB Stored Procs to insert data. As MODELS project is referred to the rest 3 , I will be able to transfer Objects across them.
Here are my questions below.
1) Can I use the same web API project above to create views of my desktop application and call the API controller methods on events like button click?
2) I don't want to expose the implementation of my business logic in CORE application to any other referencing projects. But still i need to follow a layered architecture.
How can i achieve that. Please explain with an example.
3) Is there any best architecture that i can follow with the above requirements.
4) Is this a valid architecture for WEB API and will this work?
Please take the Model example as UserModel {Name, Password, Email}
I assume you meant 'solution', not 'project'. Yes, you can keep mixed types of projects inside one solution, that is Web API for IIS hosting and WPF app that references your core.
This is where interfaces and dependency injection come into play. Create separate interface project to reference and use some dependency binding module like ninject or Microsoft Locator
When following any architecture pattern, remember that patterns were created for developers, not the other way round. What am trying to say, that when you follow any architecture, you - and only you - know what you are trying to achieve. Don't stick to any pattern if you don't know what are you doing and feel free to bend any pattern to your needs. For now keep it simple.
Yes.
I have a WebAPI web service, which acts as a business logic layer for client applications (WinForms and Mobile).
Now I want to create an MVC application which will act as presentation layer only, and I am having doubts weather this architecture makes sense or does it break MVC concepts.
If it makes sence, what is the right/correct way of interaction between MVC application (as a presentation layer) and WebAPI service (as a business logic layer)?
Will appreciate if anyone can give me some code examples.
It's fine if you use mvc this way, your controllers can access the webapi and serve the data to the templates.
You might also consider angularjs as views/templates and the controllers there can call the webapi for data.
While I think other answers are accurate, here is some other concerns you may think of.
First, your WebAPI is probably where your business are implemented. Indeed, you may already deal with:
Business related exception
Validation
Operations available
etc.
Your Api is what should not change, unless the business rule behind a certain functionnality changes too.
What I want to point out here is one thing:
Keep your user interface completely independant from your API
The risk of using an MVC app with a WebApi
All the code together = mutiple reasons to change the same thing
By using an MVC app, you could be tempted to package the WebApi and the MVC app in the same solution. You would also be able to deploy all your stuff together. But doing it this way, you may end up with a big bunch of code where parts are not evolving at the same speed (i.e: user interface will change oftently, but do the Api will change every time a UI fix is need. NO. And do every changes to the API will impact the UI. No.)
All code together enables shortcuts
What I mean by that, is that if everything is package together, a developer could be tempted to call some method directly instead of calling the API that should be the only valid facade. Any shortcut taken can lead will lead to code duplication, bugs, validation error, etc.
Again: do not package your MVC app with your API.
Solutions
Use a Javascript framework
The other suggestions are good. AngularJS, ReactJS, EmberJS are good frameworks. (There are other, pick the one that fits your needs) But again, it will be a good choice for your architecture because you will create a clear separation between your UI app and your API app which are separated concerns. Your business logic will be well protected, and you will be sure that your code is only call via HTTP calls, the only valid facade of your API. In other words, you make sure nobody will take shortcuts.
Use .NET MVC app in its own project
If you still want to use .NET MVC, I would suggest that you call your API via HTTP: no shortcuts. I would create a different solution and with a separated MVC project where calls to the API would be made using the HttpClient or something like RestSharp. What you want here is to avoid to bind your UI to your API code. You want to bind your UI to the contract define by the API facade (api controllers) not their implementation.
I think better, of course if it possible in your situation, to use one of the JavaScript MVC frameworks.
I think AngularJS, ReactJS or EmberJS will be the most coolest variants for your purpose. I don't think that calling ASP.MVC actions and then do another call to WEB API from there it's good idea, imho.
We've got a solution with multiple MVC web projects and now adding a client-facing WebApi project.
The API will be a much more scaled-down version of what is available through any of the web projects (though it will likely expand much more over time), so we've come to a decision-making point for how to handle the Models.
What are the best practices for handling Models across different projects?
It's my understanding that a Model in a WebApi project will, for example, use certain property attributes which are meaningless to an MVC web application. And also as an example, the Display attribute is meaningless to the WebApi, but very useful in a View.
This leads me to believe I should be creating a separate set of Models for the WebApi, but also wondering if I'm missing something.
I understand that this could be a question that may lead to a range of opinions, so I'm mostly looking for what are considered industry best practices.
In my solution where i have Web API and MVC web app, I have the below structure
Models : My Entity/Business objects. These are created by Entity framework from my database. These are almost same as my db structure. My Repositary methods (for data access) returns either a single instance /collection of instances of this classes. My data access project is a separate class library which has been referred in other places like my web api project etc..
Web API ViewModels : The Viewmodels (POCO class) specific to the Web API interfaces/action methods.
MVC Web app ViewModels : The Viewmodels (POCO class) specific to my razor views. I had even inherited few of these from the Web API Viewmodels and added additional properties as needed.
I use a separate project for the DTOs, so that the projects that need to consume them do not get into issues with circular references.
I would have the WebApi project map your models into the DTOs. If your MVC project is consuming the WebAPI output, it just needs a reference to the DTO project. This keeps you from having to refer to the WebAPI project directly.
I have the following situation: I have to create a website and a web service that will share a part of the functionalities.
This is why I do not want to write code twice.
I have thought of the following architecture:
MyApp.BusinessLogic --> here we save the DataModels to the database
MyApp.DataAccess -> DataModels & Entity & mapping
MyApp.UI.Models -> ViewModels
MyApp.UI.ServiceLayer -> Acceses the Business Logic, creates the UI ViewModels for the website, and transforms the ViewModels back into DataModels for saving with the help of the BusinessLogic Layer
MyApp.WebSite
MyApp.WS.Models - >Ws Models, these will be the objects passed between the client and the WS
MyApp.WS.ServiceLayer -> Accesses the business Logic, creates the WS Models for the web service, and transfoms the WS.Models back into DataModels for saving with the help of the BusinessLogic Layer
MyApp.WebService
Is the architecture overkill ? What problems will I encounter ? Will I have problems with the controllers in the ASP.NET MVC website ?
When I design my applications I do it like this. My only issue is the dull copying of models to view models. The best way to overcome this to use AutoMapper.
I would though create some unittests because there is a high risk of breaking the app when changing the services (and visa versa). Unit testing would tell you that early on.
Define basically :)
If you want to reduce the code usage, why not create your service, then just consume it in the app?
So if you would have something like...
Foo.DataAccess
-Foo.BusinessLogic
--Foo.ServiceLayer
Then have that referenced by:
Foo.WebService (including models for view/update... but probably simplify externally)
Then use
Foo.WebApp
and have this consuming Foo.Webservice to make the data calls on it's behalf
Having UI and web service models increases your code duplication, you could use something like Fluent validation to let the service handle your validation, and enhance the basic validation system.
In my Visual Studio solution I m having following types of project:
Class Library - BusinessLogicLayer
(I m in doubt how to seperate functionality in BLL)
Class Library - DataAccessLayer
(I m in doubt how to seperate functioanlity in DAL)
Class Library - DataModels
(Contains various models like User,TimeTable,Address, etc.)
WCF Service App - To create common WCF service which can be consumed from jQuery(Web App) and WPF App
ASP.net WebForms Project - Web Pages
WPF Project - Windows application for same (As it is the requirement)
Setup project - Septup project to create installer for Windows app
UnitTest project - Project to make NUnit basd test cases
Can u please tell me whether or not I m going right way?
This is my first n-tier based application.
I m actually not clear to seperate functionality in layers even in my very first screen that is login screen.
It could be like this way from code behind file login.aspx.cs in OnClick_submit event I should create instance of UserBLL class and then I should call obj.validate(username,password) which returns a model of UserInfo. While that BLL class should itself call UserDB.Validate(username,password) method which returns model back to PersonBLL class.
If I use this scenario then every operation needs a seperate db conenction.
I also want to asks whether or not creating applications in this layered approach results in any extra memory consumption.
Please explain the scenario to me if you are familiar with this.
I don't know about others but I find working code to be a far better way of getting a handle on best practices. Therefore , I'd strongly recommend downloading the Patterns and Practices Data Access drop on Codeplex. It's a little old now but will provide you with a comprehensive reference sample for a Web (albeit MVC), WPF and tiered Services application.