Why is MVC stateless - How to explain? - c#

While explaining concepts of ASP.NET MVC to my students
MVC is stateless. It is built on top of another stateless
protocol - HTTP and HTTPS
But one student interrupted and asked,
You tell that the MVC is stateless
Stateless protocol never cares if the response comes back or not from
the server. But, in ASP.NET MVC framework, you make a request and wait
for the response. Since you wait for the response, it should be called
as a stateful service. How come you are calling it a stateless service
then?
I really got stuck up and wondered what to answer to this question.
Any ideas?

MVC is not stateless, HTTP is.
HTTP being stateless doesn't mean it is fire and forget. The client does wait for the response. It is stateless in the sense that two successive requests have no relation whatsoever.
State can be emulated using sessions, for example using cookies.

The assertion in the question, purported by the other student it wrong. A stateless protocol like HTTP sure does care if it gets (or never gets) a response!
[A stateless protocol] treats each request as an independent transaction that is unrelated to any previous request so that the communication consists of independent pairs of request and response.
Of course, MVC isn't even a protocol .. but the same notion can be extended. It is "stateless" insofar as all the information is encoded in the request and response as a "pair". In practice, most usages are not truly stateless.

Please keep in mind, that there are a lot of different implementations of the concept of a model-view-controler architecture. There is no "correct" MVC. ASP.NET MVC cannot be is not a "perfect" implementation of the model-view-controler pattern!
Otherwise of thinking of stateful/stateless MVC. MVC can be understood by thinking of responsibilities:
The View is not allowed to change the state of the model directly - only through the Controller. The view can still have some direct access to the Model although only for viewing (or by having a copy that isn't the official Model).
The Model should live in its own universe and not have any reference to controllers or to views.
The Controller controls the state and access to the Model.
How they all interact with each other, can be implemented very differently (based on the platform for example) ...

MVC is not a protocol is a software architectular pattern.
On the other hand, HTTP is a protocol.
In nowadays the MVC pattern is very popular among many web frameworks. These web frameworks and the rest of other web frameworks are used for the development of web applications.
In the context of web applications HTTP is an application protocol that is used from browsers for their communication with the servers that host web applications.
Indeed the nature of HTTP is stateless. There isn't anywhere in HTTP the concept of state. For this reason, in many web frameworks, there are different ways through which we try to implement the concept of state. For instance in ASP.NET Web Forms the ViewState was developed for this reason.
That being said, MVC has nothing to do with the stateless nature of HTTP.

Related

What is the advantage of using Web API in a ASP.NET MVC (5) project?

I am implementing an enterprise web application in ASP.NET MVC 5. In many situations I am writing AJAX gets and posts and communicate with the server app. Currently I am writing controller actions to serve those requests, typically returning with JSON result. The action methods parameter binding also seems work seamlessly when I passing JSON at client side.
I do not want to go far with a not appropriate practice, so the question arises, what could be the advantage to add Web API support to my project, and refactor my current ajax - controller practice?
There are few advantages according using WebAPI over MVC + Ajax:
Internal serialization
WebAPI has an internal serialization, which makes returning specific data much more easier, without your own extension method or making your controller dependent on the serialization framework library.
Action result helpers
You can use plenty of action result helpers like Ok(), NotFound(), InternalServerError(), which all return IHttpActionResult, what makes your code easier to read and maintain and clearly state your intention.
Action result abstraction
Using IHttpActionResult you can easy abstract result, which is helpful when unit testing your controllers.
Available to self-host
Using OWIN you can easily self-host your WebAPI project, what makes your application much easier to maintain and IIS-independent.
Native attribute routing
WebAPI has implemented attribute routing which makes all routing configuration much more easier(and helps when using feature-based architecture).
DI configuration improvements
Both WebAPI and MVC have their own composition roots and different DI implementation. Microsoft has introduced some improvements in WebAPI to make it easier to use and maintain.
I'd say that using MVC + Ajax was viable only when WebAPI didn't exist because there was the only option.
If your project clients needs data in multiple formats (json,xml,csv) or have chance to change in future Wep Api needs minimal configuration comparing to mvc. Wep Api returns data to client according to content negotiation (if client needs xml returns xml,if json return json according to request header ) but in mvc you need more code to satisfy that.You have to explicitly specify data format when writing action methods.(JsonResult,ActionResult,XmlResult)
Wep Api gives you more meaningful idea about what you are doing when you look at the code later.Comparing method signatures;
public List<Student> Get() has more meaning than public JsonResult Index().
Light weight & Easy to use.
Less data transfer between client and server.
Using webapi we can develop cross domain application.
Less configuration needed as compared to WCF.
It’s simple, scalable and robust because it supports all the MVC features such as routing, controllers, model binders, IOC container, action results, filter, or dependency injection as it is built on top of Asp.Net MVC.
Empower the developers by handing over control over the way HTTP protocol messages are sent and responded to.
Unit testing is easy as it support test driven development.
It provides ample flexibility in web API creation due to content negotiation and drives support for the ASP.NET routing.
Unlike WCF REST services, there is no need to define tedious configuration settings for different devices.
The architecture of web APIs is very light, which makes them a perfect alternative for the developers when they want to build applications for devices with limited bandwidth.
Web APIs are used to create non-SOAP-based HTTP Services, so if there is a requirement for web services, but not SOAP, then ASP.Net Web API is great to look for.
Supports different message format like json, plain text and xml.
Asp.Net Web API supports convention-based CRUD Actions since it works with HTTP verbs GET, POST, PUT and DELETE.

Difference summary WCF and Web API

I'm looking for the difference summary between ASP.NET MVC Web API and WCF Service.
I've seen this question What is the difference between Asp.Net Web API and WCF Service?
and this question WCF vs ASP.NET Web API too, but they don't summarize what I can achieve with the one, what I cannot achieve with the other.
Both can be contacted via url, I first thought that was a difference between them.
So in short:
What can I do with WCF what I cannot do with ASP.NET Web API and visa versa?
this list is by no means exhaustive.
Things WCF does that you cannot do (with ease) using Web API.
Supports SOAP based XML format.
Supports strongly typed data contracts.
Supports a single point of metadata information exchange using WSDL etc.
Supports varied bindings like TCP, Named Pipes, MSMQ, even UDP etc.
Supports varied hosting options like console apps, WAS, IIS, Windows Services.
Supports one way messaging, duplex, message queues out of the box.
Supports multiple authentication schemes like Windows, Forms, Certificates etc.
Things Web API does that you cannot do (with ease) using WCF.
Supports the full features of HTTP. (Uri based access, Http Requests/Response, Http Caching etc.) To do this in WCF you need to additional work to configure it as REST service etc.
Is Lightweight with minimal configuration.
Supports the Routing, Controller/Action MVC paradigm, Model Binding etc.
Basically Web API is an easy way to do RESTful services over Http without knowing much about Web services.
To do the same in WCF, you need to do additional work in terms of httpBindings, UriTemplates, Verbs etc. And that means, understanding WCF first. And then using WCF to implement a RESTFul service over http, which is what Web Api provides out of the box.
This is not a summary per se. Its a sort of practical guide I hope.
For me it ultimately boils down to how simple I want my front-end application code to look like, and also something to do with how to achieve maximum productivity.
Traditional WCF over http is SOAP based messaging protocol. You add a service reference in your project, and Visual Studio takes care of generating the proxy classes. And you work with the instance of the proxy classes. So when you are writing your front-end code, you have intellisense to help you. Don't be fooled. This is just the IDE making life simpler for you. Underneath its pretty complicated. But my productivity is boosted to a degree. I don't have to write proxy classes. Hence, this is what I'd opt for a c# based front-end.
Alternatively, if I had to deal with a Webapi endpoint, I do not have the luxury of any IDE generated proxy classes. Therefore I'd have write code for everything. Typically I use the HttpClient classes to talk to my web api end points. Hypothetically, I could write a proxy classes to talk to web api. But it isn't as simple as in your wcf case where they were auto-generated for you.
On another line or reasoning, if my front-end was JavaScript, then my only best bet is have the web service hosted over web api, rather than wcf. If I were to talk to wcf endpoints from Js, that would be a PITN.
So it ultimately rests on your product plan, design, project schedules, etc software development plan. All the best.

Kendo + Web Api vs. MVC vs. Web Service Where to go?

I'm just starting a project where I would like to use Kendo UI (based on jquery) with C#. A few weeks ago I was successful in handling requests using Web Services (asmx), was pleased with the results and performance, and was able to create forms quickly.
Since this is a new project, I thought I could look into different concepts such as MVC and WebApi. I found MVC to be the most complicaded so I went for WebApi and started playing with controllers and requests. So far what I'm finding (don't judge me, I'm new to these new concepts), is that Web Service seems to be simpler and more flexible.
So I guess what I'm looking for is... what are the main advantages of using MVC vs WebApi and even vs Web Services. Are there any downsides to Web Services? Would it be a bad practice to have my data layer controlled by Entity Framework, all models defined, and my requests handled by Web Services?
Any clarifications are welcome. Thank you.
In a broader sense, Web API is used to create Web Services ! It uses HTTP as its standard for creating services (instead of SOAP like in asmx) as its more open and any type of client like a mobile app, desktop app, web app etc will understand HTTP protocol. Another advantage is that u can easily use JavaScript/jQuery to communicate with your Web API. With SOAP web services, its a nightmare!
Kendo UI and Web API is a great combination. We have recently created a mobile iPad app using this combination and it worked like a charm. We also used Entity Framework with oracle as back end DB and it never gave any issues.
Webservices are nice if you have the need for it. A need as in needing that logic/data in more than one different type of application (such as web, and a mobile app, and a desktop app). (Or if you want to sell the service you're providing)
Using a webservice for ONLY a website which you don't except to expand to other things is complete overkill.
Furthermore, the MVC framework and the Web Api framework are pretty similar except web api is used exclusively for webservices. Coding in both of them will be the difference between white bread and wheat bread.

How do I implement WCF with Silverlight, supporting both ASP.NET session state and SSL?

We have a Silverlight intranet application using old web services, and I've been tasked with adding support for SSL. To do this I was planning to ditch the old web services and replace them with a new WCF service.
I also needed to get rid of the old web references and build the proxy dynamically as well (because the endpoint will vary), and found this useful article which outlines how to build dynamic proxies http://sonyarouje.com/2010/10/01/proxy-less-silverlight-wcf-communication.
I now have that working (although I now need to work out how to call a method that has parameters) but I've just discovered that (a) Silverlight only supports BasicHttpBinding (i.e. not ws), and (b) BasicHttpBinding does not support session state.
Our application currently uses session to keep track of and queue up requests through our singleton data access layer. The only thing I can think of doing at the moment is to write my own implementation of session - but I was wondering if there's a better solution that I'm missing, hence this post.
So basically, is there a 'best practice' approach that supports Silverlight, WCF, session state and SSL, or am I right to go ahead and replace session with my own equivalent?
I think you've mixed WCF session with ASP.NET Sessions. WCF Session and ASP.NET sessions are completely different.
In your case, to enable ASP.NET state in WCF service, you'd just require to enable ASP.NET Compatibility Mode on service,
Please find a very good blog on the same by wenlong,
http://blogs.msdn.com/b/wenlong/archive/2006/01/23/516041.aspx
HTH,
Amit

talking between Web services and MVC Framework

I am new to MVC and Web Services.
According to my project, I have to show listing data at ViewLayer.
The listing data which I have to show will come from other region via its web service server.
It means that I have to communicate with these web server which is separate with my web application server.
Moreover, my web application have to update some of the data and send this updated data to there web service server again.
That is my project requirement.
So I have searched every possible solutions. Then I found one at stackoverflow.com. According to this, I found that I need to use $.ajax { url: ... } style which I think I need to fully rely on view layer.
Then I had found another solutions which I think I need to fully rely on Controller Layer. I mean I have to write all the code which need to talke with web services only at controller layer.
As I am junior to MVC, I could not decide which one is suitable for me.
Every suggestion will be really appreciated and welcome your any suitable solutions more.
As with all things development - it depends!
If you own the services, they hang off of the same domain, and you're mostly focused on rendering the results of the web service call to HTML, the client-side AJAX calls work well.
If they're on a different domain (or even subdomain), or you want to do more than "just call" the service (e.g., clean up the response, add some tracking, transform it in some way) then handling the web service call via the controller is probably the way to go. You can also easily add server-side caching and logging with this option.
You could use the Unobtrusive Ajax Helpers in MVC3
http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-ajax.html

Categories