Asp .NET Web API using MVVM pattern - asp.net

I'm trying to understand how I should use the MVVM pattern for a CRUD operation. Currently I have methods in my API controller such as below. My question is: using MVVM pattern, should I still build my api like that (e.g., accessing DB)? Or should it be changed? If nothing changes, in which case I would implement ViewModels and how they should be managed by the API? I made some researches but it's still not clear for me.
public IHttpActionResult GetProduct(int id)
{
var product = _context.Products.SingleOrDefault(p => p.Id == id);
return Ok(product);
}
[HttpPost]
public IHttpActionResult CreateProduct(Product product)
{
...
_context.Products.Add(product);
_context.SaveChanges();
return Created(new Uri(Request.RequestUri + "/" + product.Id), product);
}

I think part of the problem is that you don't understand the role of MVVM in a web application. To understand, you have to look at a web application as composed of two separate applications--the server side, and the client side.
Server side, the pattern being used is MVC (not surprising, it's called ASP.NET MVC for a reason). If you're trying to fit your understanding of MVVM around the MVC pattern--don't. It doesn't apply. The MVC pattern on the server is simple to understand and implement; don't try to crowbar any MVVM into it. Just design your server side code using the server side pattern.
Client side is a different matter. By default, ASP.NET MVC using Razor pages renders your HTML on the server and delivers it for display to the client. And, typically, that HTML is designed to respond to users interaction with the page by posting back to the server. Your controller methods interpret these postbacks, perform the required logic, and render the correct razor page in response. But this isn't the only way to write a website.
More and more common, people are designing Single Page Applications. These use ajax callbacks to send the result of user actions back to the server, and then process the response. Server side, these requests are almost always handled through a WebApi controller method, not an ASP.NET MVC controller method. The request comes across the wire as ajax, and the result is usually returned as ajax. No HTML gets rendered. This is where MVVM comes into play.
Client side, these web pages typically use a javascript MVVM (ish) framework, like knockoutjs or angular. The response json is used to update view models that are bound to HTML elements in the web page. These frameworks handle synchronizing updates and user actions between the UI and these view models, just like Bindings synchronize updates between the UI and your view models in WPF.
Simply put, MVC is its own thing, and MVVM usually only exists within the client side of a website, and usually only when the website extensively uses ajax callbacks instead of postbacks.
And, to answer your direct question, if you're using MVVM on the client side, using ajax calls to perform your CRUD ops, you should design your WebApi controller methods to Post/Get/Put/Delete your data.

Personally, I always use the Repository Pattern for anything to do with CRUD operations, such as interacting with an entity in a database.
I would create a separate class called "ProductRepository" and put all the methods to Get, Create, Update, and Delete a Product in that class. This way, only your Respository cares about the details of interacting with the database and performing the CRUD operations on it. Your entire application should not care about how this gets done, only your Repository class. This is something known as the Single Reponsibility Principle. It is part of the "SOLID" principles of design and architecture.
Then, in either your Controller or ViewModel or where ever you need it to happen, you just have to instantiate the ProductRepository and use its methods throughout your application.
If you use a separate Web API for your service layer and data access layer, then you don't really need MVC. You just need a front-end framework to consume the Web API URLs, like AngularJS or any other JS framework of your choice.
If you want to use MVC, then you don't really need Web API. You can just build your service layer and data access layer into the MVC application, or build them as separate projects (class libraries) and include them in your overall project solution. It all just depends upon how you want the architecture to be and how complex you want to go with it.
But either way, a "ProductRepository" should be involved -- whether it is in your Web API (if you go that route), or in your MVC project (if you go that route). The ultimate goal is to have separation of concerns. You want to separate your business logic layer from your data access layer. You don't want to be making direct calls to the database throughout your entire application. That will result in code that is very tightly coupled and hard to test and maintain over time. If you ever change out databases in the future, you only want to update one place in the code, instead of many places.
Hope this helps you out some! Best regards and happy coding!!!

Related

How to use a WSDL with ASP.NET Web API

Please let me know if the premise of my question even makes sense...
I have a WSDL file from an existing (locally served) web service. I would like to "wrap" that web service with a Web API so I can easily make RESTful AJAX calls to it. If I add the WSDL as a Service Reference, I can write controllers and make calls.
I guess my questions are two things:
Is there some easy way to expose all the WSDL actions without manually writing controllers for each one?
Is this even a good idea in concept? Is there a better way to create a nice client AJAX relationship that I'm not thinking of?
Yes, it is a good idea in concept. Abstracting the ASMX for the clients and providing an easy REST based endpoint is good.
I'm assuming the ASMX is a separate component in itself and doesn't share any Middle-tier code with your Web API project.
It is okay to abstract out the ASMX.
As for an easy way to expose all the WSDL actions as controller actions, how many Web methods are we talking about?
Typically we only have a single ASMX web service with a few web methods. (5-15)
If you have just a few, creating a single controller with 10-15 actions should not be that painful.
On the other hand, if you have unmanageable number of web methods, you might want to think of Text Template files (.tt) to generate controllers out of 'Reference.cs' files. (proxy file) i don't think there are auto-tools to convert asmx to a web api controller.
i have found it easier to hand-write the web api controller due to the nitty-gritty of the request/response types, return types, [FromBody] [FromUri] attributes, HttpPost, HttpGet attributes, and of course the action definition itself.
The text template logic could get error-prone trying to figure out HttpPost actions vs. HttpGet etc.
Also, a good controller will end up having injected dependencies for Data Access, Caching etc. and you would want direct control on the class, rather than being created by an automatic tool.

Separation of Concerns and API Controllers in MVC 4

I'm trying to build my first enterprise ASP.NET MVC 4 web application, and I'm having some issues figuring out the correct flow of things.
Let's say I have a view Clients.cshtml, which has the corresponding ClientsController, base class Controller.
I want the Clients view to display a list of all clients in the system.
Because of Separation of Concerns, I believe the correct place to handle such a request would be an ApiController, not the Controller itself, which I believe should be more or less restricted to UI tasks. So, I add the method getClients() in the ApiController which will return a JSON object containing all the clients.
Now, how do I consume this from my View, or my Controller?
A way, I believe, would be handling it using javascript; when the View is loaded, I call the ApiController using jQuery and such, and display the results asynchronically.
But I am not sure this is the correct approach, is it? I believe it is one approach, but I'd like to know alternatives, or better (more conventional) ways of handling this.
Thank you
It isn't necesary to develop a Web API, if you won't use that API in other web apps or mobile apps.
A Web API is intended to be an easy way to have a single core for several consumers, for example android apps, iOS, web apps or even custom third party consumers.
So if your app won't be used that way you don't need to use API Controllers.
If you want to separate concerns, I recomend you to create a different project (a Class Library project) in the same solution, that project would be your internal API. Then your MVC project will consume your internal API, trying to keep your controllers as skin as possible. I recomend you to read this article (it's for Ruby on Rails, but all the concepts apply to MVC .NET).
It seems like what you're looking for is a way to surface the same data to both your views (server-side rendering) and your javascript (through a JSON API).
There are multiple ways to go about this. As you mentioned, you could create a separate API controller, but in my experience this is a little smelly once you grow beyond a handful of API calls. Ideally, you'd want your API to have the same RESTful architecture as your normal controllers, which means you'd be repeating a lot of the same logic for adding, listing, and removing objects.
A good alternative I've found is to allow each controller to return either a view or JSON, depending on the format of the request. This could be expanded to include XML, CSV, or any other formats you'd like to consume from a client. There's an excellent blog post by Michael Morton about this approach. It may not be exactly what you're looking for, but the end result looks something like this:
public ActionResult Index()
{
List<Client> clients = db.Clients.ToList();
return RespondTo(format =>
{
format.Html = () => View(clients);
format.Json = () => Json(clients);
});
}

how to wire-in domain event handlers in multi-layer applications

So my question is very much related to this one: Entity persitance inside Domain Events using a repository and Entity Framework?
EDIT: A much better discussion on the topic is also here: Where to raise persistence-dependent domain events - service, repository, or UI?
However my question is rather more simple and technical, assuming that I'm taking the right approach.
Let's suppose I have the following projects:
MyDomainLayer -> very simple classes, Persitence Ignorance, a.k.a POCOs
MyInfrastructureLayer -> includes code for repositories, Entity Framework
MyApplicationLayer -> includes ASP.Net MVC controllers
MyServicesLayer -> WCF-related code
MyWebApplication -> ASP.Net MVC (Views, Scripts, etc)
When an event is raised (for example a group membership has been granted),
then two things should be done (in two different layers):
To Persist data (insert a new group membership record in the DB)
To Create a notification for the involved users (UI related)
I'll take a simple example of the last reference I wrote in the introduction:
The domain layer has the following code:
public void ChangeStatus(OrderStatus status)
{
// change status
this.Status = status;
DomainEvent.Raise(new OrderStatusChanged { OrderId = Id, Status = status });
}
Let's assume the vent handler is in MyApplicationLayer (to be able to talk to the Services Layer).
It has the following code:
DomainEvent.Register<OrderStatusChanged>(x => orderStatusChanged = x);
How does the wire-in happen? I guess is with structuremap, but how does this wire-in code looks exactly?
First, your layering isn't exactly right. Corrections:
Application Layer - ASP.NET MVC controllers are normally thought of as forming an adapter between your application layer and HTTP/HTML. Therefore, the controllers aren't themselves part of the application layer. What belongs in application layer are application services.
MyServicesLayer - WCF-related code. WCF implemented services are adapters in the hexagonal architecture referenced by Dennis Traub.
MyWebApplication - ASP.Net MVC (Views, Scripts, etc). Again, this forms an adapter in a hexagonal architecture. MVC controllers belong here as well - effectively they are implementation detail of this adapter. This layer is very similar to service layer implemented with WCF.
Next, you describe 2 things that should happen in response to an event. Persistence is usually achieved with committing a unit of work within a a transaction, not as a handler in response to an event. Also, notifications should be made after persistence is complete, or in other words after the transaction is committed. This is best done in an eventually consistent manner that is outside of the unit of work that generated the domain event in the first place.
For specifics on how to implement a domain event pub/sub system take a look here.
My first recommendation, get rid of the notion of Layers and make yourself familiar with the concept of a Hexagonal Architecture a.k.a. Ports and Adapters.
With this approach it is much easier to understand how the domain model can stay independent of any of the surrounding concerns. Basically that is object-orientation on an architectural level. Layers are procedural.
For your specific problem, you might create a project containing the event handlers that project events into the database. These handlers can have direct access to the database or go through an ORM. You probably won't need any repositories there since the events should contain all information that's needed.

asp.net mvc as a restful service and an application?

Currently I am working on small application in asp.net mvc. It is a some kind of localization tool. Our clients login on our application and they can translate terms that shows up in our applications that they use. It is happens like this:
login to localization site
find and translate certain terms for example title for button in "Catalog" application
start that application(for example, "Catalog" application from 2.) and trough web services they update local database of terms with these that are translated
It is our old solution and that works fine.
But now, I am doing refactoring of a translating tool application in asp.net mvc and I think, why we have separate logic(doubled) in mvc and in web services? Why we can't use only mvc as a web service...this way I have only one logic(fetching elements and updating) and we don't need to create wcf web service or something. And most important, I don't have mesh desktop applications with dependency on dll's in which I have this logic.
And now the question. What I can get from controller in mvc, except of views and JsonResults...can I get collections of my objects directly?
Or more plain question, how I can use asp.net mvc as a web services. What is your experience?
cheers
Marko
It really depends on your needs. You can most certainly use an ASP.NET MVC application as a data service, but it sounds like you should tease out your shared code into a common library and reference that library in both applications. There are some things that web service projects provide that would be more difficult purely as a controller action. (de/serialization, wsdl, etc...)
It really depends on what will consume your web service.
For example: jQuery consumes JsonResults well because i can return complex objects (with collections, arrays, nested objects etc) from an action and have jQuery deserialize it back to javascript object for use in the clients browser. Of course you loose type safety with the serialization process but that's pretty expected in most REST/SOAP based web services. If you really need the type safety for the consuming application, stick with WCF (or similar).
I'd just create a flag to return an action as Json. I've noticed a few sites do it this way. Say you have this action:
public ActionResult GetPeople()
{
IList<Person> result = svc.GetPeople();
return View(result);
}
..this action's result is normally rendered into some view. That's great, but if you want to use the action as a web service, you could simply change it to this:
public ActionResult GetPeople(string ajax)
{
IList<Person> result = svc.GetPeople();
if (Convert.ToBoolean(ajax))
return Json(result);
else
return View(result);
}
..so if your consuming app didnt mind the serialized Json then instead of invoking the GET request like this http://domain.com/controller/GetPeople (as a browser would to get the View), you'd just add the ajax flag like so http://domain.com/controller/GetPeople?ajax=true to return the Json. A more appropriate flag might be 'json' instead of 'ajax' - 'ajax' is common because this method is used to support downlevel browsers for actions that may optionally be invoked with ajax.
I've been thinking of adding this to my mvc app for a while but i don't like the idea of modding every action with this flag and add more if statements. My idea is to create a custom attribute to decorate actions that you want this functionality for and the attribute dynamically adds the extra flag and conditionally returns the model data as Json rather than what's originally specified. Give it a go.

What's the best way to implement an API in ASP.NET using MVC?

I've been a longtime ASP.NET developer in the web forms model, and am using a new project as an opportunity to get my feet wet with ASP.NET MVC.
The application will need an API so that a group of other apps can communicate with it. I've always built API's out just using a standard web service prior to this.
As a sidenote, I'm a little hesitant to plunge headfirst into the REST style of creating API's, for this particular instance at least. This application will likely need a concept of API versioning, and I think that the REST approach, where the API is essentially scattered across all the controllers of the site, is a little cumbersome in that regard. (But I'm not completely opposed to it if there is a good answer to the potential versioning potential requirement.)
So, what say ye, Stack Overflow denizens?
I'd agree with Kilhoffer. Try using a "Facade" wrapper class that inherits from an "IFacade". In your Facade class put your code to consume your web service. In this way your controllers will simply make calls to the Facade. The plus side of this being that you can swap a "DummyFacade" that implements the same IFacade interface in that doesn't actually talk to the web service and just returns static content. Lets you actually do some unit testing without hitting the service. Basically the same idea as the Repository pattern.
I would still recommend a service layer that can serve client side consumers or server side consumers. Possibly even returning data in a variety of formats, depending on the consuming caller.

Resources