MVC as a presentation layer only - c#

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.

Related

Restful service layer with MVC

I need a advice on creating a architecture where i want API layer in between UI layer and Business Layer. UI layer should only consume rest services for displaying data.
Reason for doing this is that we need to expose same service for others clients like Ipad, Android etc.
Now my question is:-
1) Do we need dependence inject in this case? (i don't think so coz we are not going to use any reference at UI layer. The only thing is, we are manipulating the JSON returning by service.)
2) Will it hurt performance?
3) Is this the right approach?
Any help will be appreciated. Thanks
we're doing roughly the same thing now.
1) No, you can't.
2) No, twitter is api first, they seem to be doing ok. I guess technically it will, but it does mean you can scale horizontally so the extra hop overhead can easily be counteracted.
3) You have multiple ui clients so it seems like a decent viable solution.
Security
Security: Basic Authentication
Its the easiest to setup, but be aware the token is reversible, so use HTTPS to encrypt the communication.
The HTTP Authorization header containing the username and password is sent with every request to the api level.
You could use session but that requires a bit more setup.
There are plenty of how to's on setting up basic authenication in C# and web api.
The way i created an API for me was:
Project 1 : WebAPI serving as a portal to fetch data
Project 2 : Class Library, providing services to the WebAPI layer.
Project 3 : Class Library, providing data to my services layer using EF.
Now, different controllers in the web api project require different service objects(from project 2) to work with. I had to provide constructors for those controllers using DI. for this i used Autofac.
For you, your business layer would be Project 2.
Data flowing through one more Project layer might take some time, and you will need to put up exception handling and logging again in the API layer. i don't think performance should be big problem here.
In my experience I've seen such platform oriented approach - providing mSOA to N amount of clients. The architectural solution was a Facade that was hiding all the complex Business Layer requests and in the same time providing UI insensitive processing.
Will it hurt performance?
Not necessary - since it has knowledge of how to handle all required sub-systems requests. All the clients just know that they need a single JSON contract to get the job done, not which and how many of the services to call. By doing so - we have a much better and simplified communication. Take a look at the Mediation (intra-communication) pattern:

web api controller in n-layer architecture

In my n-tier .Net Application I got next layers:
Data Access Layer (EF)
Business Layer (Validation & Business Logic)
Presentation Layers (1 MVC Controller and many API Controllers)
I found, that my Business Services only validate business objects, call CRUD DAO methods and return results to Api Controllers.
So, I doubt: may be Web Api Controllers should be used as Business Services?
Interesting, just answered a similar question...
So I woudn't do it I were you.
Here's just a few disadvatages of the approach from the top of my head:
Performance - a redundant HTTP roundtrip in Web MVC project.
Separation of concerns - most of the time the functionality provided
by API differs greatly form UI for the same project/application. You
might want to limit the API to a few methods with a strict contract.
In case you want Web API to be a layer between Web MVC and your DAL
you will have to expose all functionality you need for UI as well.
Also you might want to have different authorization and
authentication mechanisms. Very often API exceptions handling is
also different as well as input validation.
Maintanance - everytime you need to make a change required for UI
only you have to make sure it doesn't brake your API clients. Also
API versioning is a very important topic and mixing it with most UI
changes makes this process even more difficult.
Probably for now you application is not that complex but from the design perspective your solution is much more flexible now than it will be if you decide to put Web API between your UI and DAL layers.
N-Tier applications and multi-layer are not popular among the new wave of developers. Keep in mind, that just because something is not popular, among a group, does not mean that it does not have merit.
Pros of MVC:
Separation of Concerns
Unit Testing
Does a multi-layer MVC application using a Web.API have merit:
I know this will be met with some discontent and disagreement. However, my concern is that single purpose application developers are not giving consideration to enterprise development. Enterprise development, load balancing, manageable code maintenance, and true Separation of Concerns are only possible with multi-layer applications that can easily lend themselves to N-tier.
Many developers are operating in environments that demand that they design and implement data structures in SQL, create and maintain models and CRUD functionality, develop controllers and design good looking and friendly views. The MVC model utilizing Entity Framework makes this a manageable task for these small to moderate platform developers.
In the Enterprise, separating the Business and Data Access layers from the User Interface makes real good sense. Right now MVC is a popular and very functional platform for efficient and usable User Interface development. What will be the UI platform in ten years? Separating the UI from the other layers gives more life to the work spent developing the business logic. Not to mention, that it allows for accessing data on multiple platforms today.
Multi-layer MVC using Web.API has these advantages:
True Separation of Concerns
Supports Unit Testing
Makes the Business logic and Data Access logic more scalable and reusable than MVC alone.
Supports data processes without page refresh. (REST)
CONS:
- Does not easily support use of Entity Framework. (Which is not ready for the enterprise yet anyway)
You could have your code as part as your model, and that would even be considered as good separation of concerns since MVC is build for that.
But what my preferred thing to do is keep logic in a Business Layer of it's own. The reason for that is, I think, better separation of concerns. I like using IoC, so there might be different configurations that I route thought different running solutions. Or, I might have another UI/API/Project that uses the same logic layer.
As for the overhead, it has a little overhead, but I think worth the trouble comparing to the actual overhead in code it creates.
I agree with others here, looking into using strongly typed views, the controllers would only create an instance of the viewmodel and send it on to the view. The view model then is the intermediary to the data services layer. I personally create all my entities using EF in a different project just to separate function. The view model can either call EF directly or you can add another layer of pre-canned EF queries which the Viewmodel uses just to populate the view collections. This would look like this:
[View]-[Controller]-[Viewmodel]-[Optional repository and interface to EF]---[EF]
In the interface to EF you would catch all DB errors when trying to get information and post back to the view according to your design.
The beauty of strongly typed views is that they post back and forth from the View and can contain methods which you can call at will. Because they are a pseudo model for the view, they can also have properties specific to the view which may be used at the business layer. I pass view models around quite a bit were warranted. (After all they are just a pointer)...
You can implement business logic/validation/calucations in the actual model/entity classes rather than ApiControllers, otherwise you will end up with so much code in your controller which is not really a good thing.
Also you can use DataAnnotations Attributes to perform your validation which sits outside of your controller. for.e.g. http://msdn.microsoft.com/en-us/library/ee256141(v=vs.100).aspx

Strategy for a central Web API application to serve multiple .NET front-ends

I want to finally decouple as much as i can my existing ASP.NET MVC projects.
They use multiple approaches as the time went by and i was learning:
Standard MVC, controller actions return separate views to browser.
Controller actions returning FAT partialviews and jquery updating pages.
Controller actions returning just JSON/XML data and jquery does the job of updating the UI
Now i want to move on to more dynamic front-ends by using heavier javascript approaches, by putting libraries like Knockout,Angular,Backbone e.t.c into the game. But i also want to be flexible enough and fast, if i want to just return a ready partialview from my controller actions.
So i was thinking of centralising my business layer NOT in the form of having common projects in my MVC projects, BUT having a Central WEB API endpoint above my business layer and DAL which will serve my various front ends (it can be MVC, console app, informs e.t.c)
This:
DAL -> Business Layer -> WEB API
After that i want to know how to connect to WEB API output from various points:
Pure JS: Directly from WEB Api endpoints with ajax calls
2. .NET apps (MVC,WinForms e.t.c): How exactly?
My question is mostly about #2 above. I want specific use cases on how to consume my central WEP API from within windows Forms or MVC controller actions
This is called a Service Oriented Architecture.
For #2, you have the following options to call RESTful services from a .NET client (be it ASP.NET MVC or WinForms):
Using an HttpClient.
Use RestSharp. This is a helper lib which covers most of the basic operations, including request/response serialization and deserialization. Note that in newer versions JSON.NET support has been removed (for some reason I'm not remembering now... anyway, it's in a Google Groups discussion).
Either way I recommend looking into the async/await pattern which HttpClient fully supports. It will make your life a lot easier, especially for the WinForms stuff.
About #1, there's nothing stopping you from having the JavaScript front-end calling into the Web API. Just be careful with CORS, as I assume you might need it (by having multiple web clients, possibly deployed on different domains).

Asp.net mvc layer division

I am new to asp.net mvc. I want to divide presentation layer with logic layer. I know it is already done in asp.net mvc but I want to have presentation layer on another machine. I don't know if this what I want to do, is possible, but just wanna ask. I want something like this: User enters address 123.123.123.123/Home then that request is redirected to presentation layer. Presentation layer is then asking "Logic Server" for data(from database or smthing) and logic server returns it back to presentation layer which presents the page to the client.
My overall goal is to make framework which allows us to do this easily.
And my questions:
1. Is it worth doing it?
2. Is it possible with asp.net mvc ?
3. Is there anything like this?
I wanna also extend that framework to work independent from technology. And the presentation layer would be a "connector"
You can do this by having some kind of Service Oriented Architecture. In your MVC app you have a services layer, this could talk to a WCF service or something similar on your network. Your WCF service would then talk to another machine for data storage, do the required business logic and return simple DTO's.
Is it worth doing? This depends on you. Is there a good reason to do this? It shouldn't be that hard, and if you write your MVC app correctly the services layer will abstract away the fact that the service is on another machine or the same machine so you have some flexibility to change your mind later.
Is it possible? Yup
Is there anything like this? I'm sure there are plenty of people out there who are doing/have done what I have described
Quite strange architecture.
You can indeed use SOA. It has many advantages and it's well studied and supported.
However, I wouldn't use SOA for the presentation layer (and I don't remember to have seen that never).
You'd normally have the business logic in a layer, and expose it as Web Services (that's SOA), and all the presentation (in this case creating MVC view models, and returning the rendered views to the browser) in the same application. (See note at the bottom)
It has no sense to separate the Presentation in a SOA layer, because you cannot reuse it for anything else. I.e. you cannot use that presentation layer for a windows application, or to use it for a java web application.
However, if your business logic is exposed in a SOA layer, then you can use it with any kind of UI you want: windows forms, WPF, or even a Java Web Application.
Apart form this there is a tigh knot between routes, and controllers in MVC. You cannot easily achive what you want to do. However, you can easily make an MVC presentation layer (routes, controllers and viewws), which uses the business layer exposed as SOA from your controllers. That's much more natural.
Is it possible: of course, but non-standard and har to do.
Is it worth: No it isn't. Your canot reuse it with a different techonlogy. Which is the advantage?
Is something like this: neve seen it!
NOTE: having a single app doesn't mean having a single layer. But you don't need to separate them in different applications or SOA layers. If you use MVC correctly you'll have a very clear separation between Views (which render the result for the browser) and controllers (which prepare the View Models for rendering the Views) and the Business layer (which can be in a different app, exposed as SOA services, and consumed from this controllers). In fact, it's hardly impossible to make a bad use of MVC if you have into account that you need View Models, which are objects specifically created for the view to be rendered, instead of using directly the business entities.
For example a vie model can have a customer's data to edit it, but probably will have several lists of options for populating drop down lists. If you don't use view models, you'll soon have problems.

Using Controllers without the entire MVC Framework

I'm in the process of trying out a few things with MVC whilst designing a system and wanted to try and see if I could use the concept of Controllers outside of the MVC framework. When I say outside, I mean within my own C# service as opposed to a web-site.
I started a simple console application to test the theory and it was simple enough to change the profile to a non-client profile, add in System.Web.Mvc, create a controller and have it return a JsonResult. The ease of which this got set up pleased me as that is half the work done if I want a service to respond with JSON.
The next step is to set up a Http Server class, and I would love it if I could leverage the other part of the framework which will map incoming requests to my controllers. Unfortunately, this is the part where I am lost and I have no idea what code goes on behind to arrive at a particular controller's function with the parameters all in place.
Has anyone got an idea on how to accomplish this, or a resource to look at?
In short: I'd like to leverage the use of Controllers in my own service, running it's own HTTP Server.
You can use the design pattern without using the framework - what I mean is, you can apply the model view controller pattern wherever you believe it solves the problem - if you think that you can replace "view" with "service", you could apply some of the concepts...
http://msdn.microsoft.com/en-us/library/ff649643.aspx
However, there are other patterns that may lend themselves better to services, although if we are talking specifically about a JSON service, then just using the ASP.NET MVC framework as it is would work well (rather than trying to re-write it).
Are you not trying to reinvent the wheel?
If returning JSON is one of your main purpose then WCF fulfills your need. Having WCF with you you are free to host it in IIS. This serves your second purpose having its own HTTP server.
You are trying to achieve some kind of routing where based on URL your different actions will be called. Isn't it similar to having a WCF service with different methods and client is calling each of them with different URL?
Trying controller concept in a non web application seems to be innovative, however in your case it looks like over-engineering.
The basic MVC pattern isn't all the difficult to replicate. I would seriously consider writing your own, rather than trying to shoehorn the MVC classes into your app.
Simon
If it helps you, the entire ASP.Net MVC Framework is open source, you can download it all from http://aspnet.codeplex.com/ . You can use the libraries here to view how the Framework is doing things behind the scenes and adapt things for your own use as appropriate.

Categories