WCF as MVC controller. model and views? - c#

I've been searching on the net for possible answer to my question, but no luck at all.
I just wonder if I could use WCF as my Controller in ASP.NET MVC.
So if I call
(WCF)
http://localhost:1621/WCF/LogOut.svc?id=10001
It will work like
(MVC)
http://localhost:1621/WCF/LogOut?id=10001
Or I'm just having wrong thought about it?
Can you give some source for deeper knowledge in MVC and WCF.. Thanks!

The MVC states that the controller picks up requests and it is responsible for preparing the model and passing it to a view which is ultimately rendered.
Although from the perspective of web requests, WCF could possibly look like MVC, there is no easy way to make WCF render the HTML to the browser. This means that if WCF can implement "controllers" which produce "models" but is not designed to create "views".
However, if your web application can pick up XML/JSON data produced by WCF calls (i.e. you have your views implemented purely at the client side) then yes, WCF does a good job as a provider of the "controller/model" part of the MVC.

Related

Shared models between WebApi and MVC

I'm making a project that uses both WebAPI and ASP.NET MVC templates. My MVC sends requests to the WebAPI where the logic happens. For my WebAPI, I have created request/response models (they are used in the services). I need an advice, if it's worth to share this request/response models for WebAPI and MVC, or if there are some good practises to do such things. Thanks!
This is actually a very common situation in Micro-Service architecture. Generally, it is best to decouple your front end from your back end, much the same way an app is when calling any other api (e.g. Spotify's api). But if you do decouple them then you will need to have a copy of the request and response objects in the calling app as well as the api. They don't have to be exactly the same but they need to be close enough to send the request with all required info, and then catch the response and deserialize it back into the object you need in the front end.
The down side is that you end up having to change models two places every time a change has to happen. That or you start creating versioned routes and gradually deprecate the old ones.
Honestly, good practice for design when you are dealing with an API and MVC is separation. Typically you would have your API completely segregated from anything else front end or client wise, as think about it, an API is a self contained system. Like any API such as Google Maps API, theoretically you could call it from a mobile app, a web application, or another separate system so you define expectations for requests and it's up to each client to match the outgoing request model.
MVC models, in the base interpretation, should be for displaying information on the client, so they should be specific to each view and what the view needs, hence view model. You may need some or all of the data to display that an API sends so it's good practice to have the model fit only what the view needs, rather than have a bunch of data in memory that you possibly will never use.
In general, I find a good approach to be have a core project framework which has shared models which match the database, data models. You can use these base definitions, think an Address model which matches a database table which will not change in meaning, to create API models in the service layer for requests/response and data access, and additionally use in definition of view models. Shared core resources but completely separate models which fit the definition of what you are doing in that application layer.

Properly exposing C# methods to jQuery

I would like to ask a question.
Recently, I've learned how to make jQuery use C# methods via consuming from an ASP.NET Web service. I am thinking of exposing some database access methods such as retrieving a list of records from the database for rendering using a jQuery library.
I have on top of my head is that I create a separate project in my solution, which is a Web service project to be able to expose the said data access methods (located on a separate project also in the solution). The web service will act as interaction between my jQuery and my data access methods.
I am visualizing my idea like this:
My question is that, is my idea a good thing to do, and if not, how do you properly expose C# data access objects for use with jQuery?
Thanks!
EDIT: The Web UI is an ASP.NET Web Forms, specifically version 2.0. I'm doing this in preparation to my next job.
Yes, this is the correct approach. Typically, the Web Service is a REST API (http://en.wikipedia.org/wiki/Representational_state_transfer) that returns JSON/JSONP. This allows the client (JQuery) to use AJAX, async calls to the server.
Web API 2 (http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api) is an easy way to expose an REST API in c#.
As Richard has already explain
i will extend it and suggest you to use AngularJs instead of simple of calling jquery ajax.
Why AngularJS?
HTML is great for declaring static documents, but it falters when we
try to use it for declaring dynamic views in web-applications.
AngularJS lets you extend HTML vocabulary for your application. The
resulting environment is extraordinarily expressive, readable, and
quick to develop.
Case Studies for example

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).

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.

Developing a new RESTful web service in .NET -- where should I begin? ASP.NET-MVC, WCF?

The objective is to build a service that I will then consume via jQuery and a standards based web front-end, mobile device "fat-clients," and very likely a WPF desktop application.
It seems like WCF would be a good option, but I've never built a RESTful service with WCF, so I'm not sure where to even begin on that approach.
The other option I'm thinking about is using ASP.NET MVC, adding some custom routes, add a few controller actions and using different views to push out JSON, xml, and other return types.
This project is mostly a learning exercise for myself, and I'd like to spend some extra time and do it "right" so I have a better undertanding of how the pieces fit together.
So my question is this, which approach should I use to build this RESTful service, and what are some advantages of doing it that way?
Normally, I would say WCF for any kind of hosted serice, but in the specific case for RESTful services using JSON as a serialization mechanism, I prefer ASP.NET MVC (which I will refer to as ASP.NET for the remainder of this answer).
One of the first reasons is because of the routing mechanism. In WCF, you have to define it on the contract, which is all well and good, but if you have to make quick changes to your routing, from my point of view, it's much easier to do them using the routing mechanism in ASP.NET.
Also, to the point above, if you have multiple services exposed over multiple interfaces in WCF, it's hard to get a complete image of your URL structure (which is important), whereas in ASP.NET you (typically) have all of the route assignments in one place.
The second thing about ASP.NET is that you are going to have access to all of the intrinsic objects that ASP.NET is known for (Request, Response, Server, etc, etc), which is essential when exposing an HTTP-specific endpoint (which is what you are creating). Granted, you can use many of these same things in WCF, but you have to specifically tell WCF that you are doing so, and then design your services with that in mind.
Finally, through personal experience, I've found that the DataContractJsonSerializer doesn't handle DateTimeOffset values too well, and it is the type that you should use over DateTime when working with a service (over any endpoint) which can be called by people over multiple timezones. In ASP.NET, there is a different serializer that you can use, or if you want, you can create your own ActionResult which uses a custom serializer for you. I personally prefer the JSON.Net serializer.
One of the nice things about the JSON.Net serializer and ASP.NET that I like is that you can use anonymous types with it, if you are smart. If you create a static generic method on a non-generic type which then delegates to an internal generic type, you can use type inference to easily utilize anonymous types for your serialized return values (assuming they are one-offs, of course, if you have a structure that is returned consistently, you should define it and use that).
It should also be mentioned that you don't have to completely discount WCF if developing a RESTful service. If you are pushing an ATOM or RSS feed out from your service then the classes in the System.ServiceModel.Syndication namespace of massive help in the construction and serialization of those feeds. Creating a simple subclass of the ActionResult class to take an instance of SyndicationFeed and then serialize it to the output stream when the ActionResult is executed is quite simple.
Here is a a thought that may help you make the decision between ASP.NET MVC and WCF. In the scenarios you describe, do you expect to need to use a protocol other than HTTP?
WCF is designed to be transport protocol agnostic and so it is very different than ASP.NET. It has channels and bindings, messages, service contracts, data contracts and behaviours. It provides very little in the way of guidance when it comes to building distributed applications. What it gives you is a clean slate to build on.
ASP.Net MVC is naturally a Http based framework. It deals with HTTP verbs, media types, URLs, response headers and request headers.
The question is which model is closer to what you are trying to build?
Now you mentioned ReST. If you really do want to build your distributed applications following the ReST constraints then you would be better to start with OpenRasta. It will guide you down that path.
You can do Rest in ASP.Net MVC and you can do it in WCF, but with those solutions, you will not fall into the pit of success ;-)
Personally, I am not crazy about implementing REST services in WCF. I find the asp.net mvc framework a more natural programming model for this.
The implementor of http://atomsite.net/ originally implemented the atompub specification in WCF and then rewrote the entire service using asp.net mvc. His experience echoed my comment above that for a pure REST service asp.net mvc is the way to go.
The only exception would be if I wanted to potentially expose a service in a restful and non restful way. Or if I was exposing an existing WCF service via REST.

Categories