We're sorry but this page doesn't work properly without JavaScript enabled. Please enable it to continue.
Feedback

REST with ASP.NET MVC

00:00

Formal Metadata

Title
REST with ASP.NET MVC
Title of Series
Number of Parts
110
Author
License
CC Attribution - NonCommercial - ShareAlike 3.0 Unported:
You are free to use, adapt and copy, distribute and transmit the work or content in adapted or unchanged form for any legal and non-commercial purpose as long as the work is attributed to the author in the manner specified by the author or licensor and the work or content is shared also in adapted form only under the conditions of this
Identifiers
Publisher
Release Date
Language

Content Metadata

Subject Area
Genre
Abstract
Creating ReST architectures with ASP.NET MVC is more than just decorating actions with verbs. It’s about leveraging HTTP as an application protocol to its full potential. In doing so, we can create robust and scalable applications, not only from a performance point of view but also in terms of change and maintainability. ASP.NET MVC offers us great potential to create ReST architectures that can be consumed by computers and humans alike, reducing the amount of effort involved. Now combined with the WCF Web API which is focused exclusively around ReSTful constraint, MVC offers us even more possibilities. Come to this session to learn what ReST is really about and how we can create simple yet powerful systems with the Microsoft MVC stack.
Representational state transferApplication service provider.NET FrameworkComputing platformScalabilitySoftware architectureInterface (computing)Cache (computing)FreewareForm (programming)Representational state transferPhysical systemSoftware developerSeries (mathematics)Projective planeConstraint (mathematics)MereologyPhase transitionRight angleWater vaporMultiplication signWeb pageLink (knot theory)Software architectureHypermediaScalabilityInterface (computing)Scripting languageWeb 2.0Java appletComputer virusThomas BayesCoefficient of determinationComputer clusterProcess (computing)Goodness of fitPoint (geometry)Heat transferView (database)Representation (politics)Scaling (geometry)Capability Maturity Model1 (number)CASE <Informatik>BuildingWordTerm (mathematics)Server (computing)Product (business)Application service providerLevel (video gaming)Different (Kate Ryan album)BijectionDistributed computingState of matterComputer animation
GUI widgetHypermediaLevel (video gaming)Capability Maturity ModelData modelRemote procedure callTime domainInternet service providerSystem callPoint (geometry)Single-precision floating-point formatSoftware developerRepresentational state transferHybrid computerOperations researchFocus (optics)Control flowState of matterServer (computing)Client (computing)Order (biology)Uniform convergenceSystem identificationEmailRepresentation (politics)Content (media)Formal languageDisk read-and-write headIdempotentComputer configurationPatch (Unix)Computer networkRepresentational state transferHypermediaRepresentation (politics)Multiplication signComputer configurationElectronic mailing listPhysical systemOrder (biology)EmailFundamental theorem of algebraInformationWeb browserLevel (video gaming)Cartesian coordinate systemMoment (mathematics)Right angleGoodness of fitOperator (mathematics)Server (computing)Uniform resource locatorFormal languageMedical imagingWeb pageDefault (computer science)Arithmetic meanParameter (computer programming)Type theorySingle-precision floating-point formatFocus (optics)Software developerBitContent (media)Identical particlesConstraint (mathematics)Covering spaceDisk read-and-write headPoint (geometry)System callUniformer RaumIdentifiabilitySet (mathematics)Coefficient of determinationDifferent (Kate Ryan album)Water vaporCAN busComputer iconScaling (geometry)Internet service providerComputer animation
Operations researchDisk read-and-write headComputer configurationPatch (Unix)Computer networkIdempotentSoftware developerCommunications protocolException handlingCodeServer (computing)Error messageKontrollflussConditional probabilitySanitary sewerState of matterHypermediaCartesian coordinate systemSoftware frameworkConstraint (mathematics)Field (computer science)Point (geometry)Multiplication signRepresentational state transferNumberCommunications protocolFlow separationSystem callSoftwareRevision controlPhysical systemDirected graphEmailOperator (mathematics)Right angleIdentical particlesInformationException handlingHypermediaLevel (video gaming)Order (biology)OscillationScalabilityCASE <Informatik>Arithmetic meanDisk read-and-write headPower (physics)Different (Kate Ryan album)State of matterDrop (liquid)Internet service providerAffine spaceHTTP cookieChemical equationContent (media)Client (computing)Cellular automatonData storage deviceParameter (computer programming)Scaling (geometry)Server (computing)Uniformer RaumCausalityCodeRepresentation (politics)AbstractionCodeSet (mathematics)Semiconductor memoryMultiplicationType theoryPattern languageError messageIdempotentData structureWeb 2.0Computer fileComputing platformLastteilungRepository (publishing)Computer animation
Software developerHypermediaState of matterCellular automatonPlastikkarteFreewareGamma functionExecution unitDecision tree learningCodeVideoconferencingWeb pageControl flowProduct (business)Right angleLink (knot theory)Cartesian coordinate systemForm (programming)Revision controlWeb pageWebsiteState of matterDependent and independent variablesDataflowComputer animation
Form (programming)Link (knot theory)Software developerDataflowScalabilityState of matterExecution unitWeb pagePlastikkarteDecision tree learningVideoconferencingProduct (business)PurchasingInclusion mapDataflowLink (knot theory)Computer programmingForm (programming)Sound effectInternet service providerMultiplication signWeb pageRevision controlInformationIterationRepresentational state transferUniform resource locatorClient (computing)Game controllerState of matterProcess (computing)Physical systemServer (computing)Representation (politics)Web 2.0Operator (mathematics)EmailSystem administratorVirtual machineWebsiteHypermediaOscillationControl flowDependent and independent variablesCartesian coordinate systemDesign by contractComputer animation
DataflowScalabilityState of matterType theoryHypermediaFile formatSoftware developerComputer programOrder (biology)InformationLink (knot theory)Codierung <Programmierung>HyperlinkCommunications protocolHost Identity ProtocolDomain nameCartesian coordinate systemHypermediaRepresentational state transferSelf-organizationPhysical systemFile formatComplex (psychology)Code refactoringOperator (mathematics)Different (Kate Ryan album)Web pageOrder (biology)Control flowInformationSocial classInternet service providerComputer programmingMultiplication signLink (knot theory)Set (mathematics)Form (programming)Instance (computer science)Representation (politics)Computer animation
InformationComputer programDataflowOrder (biology)Link (knot theory)Software developerCodierung <Programmierung>Communications protocolHost Identity ProtocolHyperlinkFinitary relationFile formatContent (media)Dependent and independent variablesRoutingUser interfaceGame controllerGroup actionView (database)Data modelGroup actionCuboidLink (knot theory)Product (business)Type theoryDependent and independent variablesPattern languageDisk read-and-write headView (database)Operator (mathematics)Set (mathematics)System callSocial classEndliche ModelltheorieComputer iconWeb 2.0Demo (music)LogicGame controllerOrder (biology)Process (computing)Right angleUniform resource locatorPhysical systemClient (computing)Office suiteState of matterNumberRepresentational state transferInternet service providerPoint (geometry)User interfaceComputing platformInformation.NET FrameworkMereologyGodEmailDataflowForm (programming)Goodness of fitApplication service providerAuthorizationServer (computing)FreewareElectronic mailing listOrientation (vector space)Computer animation
Local ringSoftware developerView (database)Game controllerPrice indexPhysical systemGroup actionOperations researchDigital filterSocial classGroup actionOperator (mathematics)Game controllerRepresentational state transferFilter <Stochastik>Orientation (vector space)Point (geometry)ResultantGoodness of fitMultiplication signComputer animation
HyperlinkCommunications protocolCodierung <Programmierung>Computer programDataflowSoftware developerHost Identity ProtocolProxy serverSlide ruleVisual systemView (database)Error messageRepository (publishing)Physical systemGame controllerSpacetimeBuildingSoftware architectureInternet forumLemma (mathematics)WindowRule of inferenceGroup actionPrice indexParameter (computer programming)Uniform resource locatorDefault (computer science)Digital filterInformationTerm (mathematics)OvalMenu (computing)Point (geometry)CodePower (physics)Group actionConfiguration spaceRepresentational state transferSingle-precision floating-point formatRootLimit (category theory)Goodness of fitTable (information)Process (computing)Content (media)Game controllerOperator (mathematics)Constraint (mathematics)Annihilator (ring theory)Multiplication signBridging (networking)RoutingCASE <Informatik>System callRight angleComputer animation
Repository (publishing)View (database)Software developerContext awarenessDigital filterWindowSoftware architecturePrice indexSpacetimePhysical systemAsynchronous Transfer ModeOvalComputer configurationConstraint (mathematics)Group actionExtension (kinesiology)Query languageString (computer science)EmailWeb pageRule of inferenceCodeFile formatCodierung <Programmierung>Dependent and independent variablesContent (media)Dependent and independent variablesCodePhysical systemResultantFile formatGroup actionCartesian coordinate systemRoutingMultiplication signRight angleFunction (mathematics)Endliche ModelltheorieSystem callFilter <Stochastik>View (database)Uniform resource locatorWeb browserWeb pageExtension (kinesiology)Type theoryRepository (publishing)Point (geometry)Game controllerComputer configurationDescriptive statisticsRepresentation (politics)Different (Kate Ryan album)Representational state transferQuery languageSubsetException handlingCausalityState of matterString (computer science)Latent heatProcess (computing)Lie groupEmailAttribute grammarSerial portApplication service providerCodeNormal (geometry)CuboidWeb 2.0RootComputer animation
EmailCodierung <Programmierung>Communications protocolSoftware developerComputer programDataflowBuildingGame controllerGroup actionPrice indexView (database)Scalable Coherent InterfaceAuthenticationSpacetimeAttribute grammarLengthData conversionString (computer science)PasswordParsingLogicDigital filterContext awarenessMaß <Mathematik>Physical systemOval10 (number)TouchscreenForm (programming)State of matterGroup actionDefault (computer science)Server (computing)System callAuthenticationPasswordConstraint (mathematics)HTTP cookieFunction (mathematics)Web browserRight angleCuboidImplementationRepresentational state transferGame controllerType theoryCodeSystem administratorThomas BayesAttribute grammarEmailMessage passingApplication service providerComputer animation
Software developerWeb pagePasswordServer (computing)Application service providerGoogle ChromeSlide rule.NET FrameworkProxy serverMereologyContent (media)AuthenticationDependent and independent variablesWindowRule of inferenceLeakData conversionCodierung <Programmierung>Data typeString (computer science)LogicDigital filterContext awarenessRepository (publishing)View (database)Data modelModal logicOvalEmailSoftware architectureRight angleCuboidServer (computing)Group actionPasswordAuthenticationApplication service providerView (database)ResultantPoint (geometry)Attribute grammarHash functionCodeWeb 2.0EmailEndliche ModelltheoriePhysical systemClient (computing)IPSecFehlererkennungIdentity managementInformation securityHookingCache (computing)Line (geometry)Matching (graph theory)Generic programmingCondition numberRepresentational state transferWeb browserFunction (mathematics)Form (programming)GodScalabilityState of matterMathematicsComputer animation
HypermediaSoftware developerMappingContent (media)Software development kitProjective planePersonal identification numberComputer animation
Host Identity ProtocolCodierung <Programmierung>HyperlinkCommunications protocolDataflowComputer programSoftware developerCrash (computing)PowerPointSlide ruleSoftware architectureGame controllerGroup actionView (database)WindowSpacetimePhysical systemPrice indexUniform resource locatorRule of inferenceDigital filterVideo GenieRoutingGeneric programmingBuildingPoint (geometry)Group actionRoutingLevel (video gaming)Cartesian coordinate systemGame controllerContent (media)Computer virusElectronic mailing listElectric generatorRootSampling (statistics)Default (computer science)Mobile appComputer animation
Representational state transferWeb browserClient (computing)Form (programming)Parameter (computer programming)Query languageEmailSoftware developerConstraint (mathematics)Series (mathematics)ScalabilityHost Identity ProtocolInterface (computing)Representational state transferLevel (video gaming)Covering spaceJava appletClient (computing)Web browserHypermediaUser interfaceGoodness of fitWeb 2.0Game controllerConstraint (mathematics)Internet service providerInteractive televisionDesign by contractFunction (mathematics)Series (mathematics)Physical systemWeb serviceLibrary (computing)Disk read-and-write headForm (programming)System callComputer animation
Transcript: English(auto-generated)
So, on, on, on. You can hear me? Yes, good. Good afternoon. Hi, hello. Good afternoon. Are you tired? I didn't get that. Are you tired?
Oh, good. It's Friday. How many of you have been here for the whole week? Including workshops. Must be tiring, huh? Right, so I'll make this session very short and sweet.
It won't be too complicated, and it'll be quite easy to follow along, hopefully. If you are here, this is a talk on REST with ASP.NET MVC. And the main agenda here is a brief introduction to REST.
Right, so how many of you here know what REST is? Have been working with RESTful systems. Okay, so we're going to rehash what REST is, just in case for the people that aren't too clear on the topic. And then I'm going to show you how you can leverage ASP.NET MVC to do REST.
Okay, or create RESTful systems. Now, one word of warning. How many of you are here to see Web API? Okay, if you are, you're in the wrong room. Right, I'm not going to show Web API. I'll explain why I won't show it later on. It's not that I don't like the technology.
It's just I think it's not relevant, or at least to this talk, okay? So don't say I didn't warn you. And cheer up, please. Really, don't be so gloomy. It's okay. Did anyone come to my morning talk? Right, everything I said, don't hold it against me.
I love you all, really, I do. Today, I'm a developer again this afternoon. So let's think web, right? And if I say to you, web, what do you think? Yeah, you're going to speak louder than that.
What else? HTTP, what else? JavaScript. You took the worst part of the web and brought it out. Pardon? Free form. Free porn. Oh, it's free?
Okay, I wasn't thinking about porn. Distributed architecture. Would you agree that the web is a distributed architecture? Would you agree that we can accomplish scalability with it? That we think about scalability when we think web?
About statelessness and cache, because those are inherent in the way the web works. A simple interface? I mean, it doesn't get much simpler than the web, right? Go to a page, get a page, post some data, get some data back. It's as simple as it gets. If you want to go somewhere, you click on a link. If you want to fill something out, you fill a form. It doesn't get simpler than that.
And loose coupling, which it allows us to do, because we have these things like server farms, and we have failovers, and we have Azure, and we have EC2, and we have all these different things that allow us to create loose coupling for our system so that one doesn't fail if the other one fails, etc. Now let's think about system design. What are the goals that we try and accomplish in system design?
Well, the big one, I hope, is maintainability. I mean, we're assuming already that the system works the way it should, and everything, and we've talked to the customer, and all that dandy stuff is all over and done with. In terms of a technical point of view, we try and maintain maintainability, right?
We try and accomplish that so that we can create a system that can work, and we can maintain it over time. We try and create a system that is reliable. For those of us that work in very, very large projects that are very successful, that are accessed by millions of users in one hour intervals. How many of you are there in this room? One? Okay.
You look for scalability, and we also try and accomplish simplicity. We try and make the simplest kind of interface. Well, no, we don't. We aim to try and make the simplest kind of interface. That's not really valid. I'll take that one out.
But if you take these goals, and you put them along the goals of the web, you kind of see that somehow you can try and match these things up. Not to a one-to-one that I've put there, necessarily, but you can try and see a common ground between what we do when we design systems and the way the web works.
So that's REST. That's it. That is the whole idea behind REST. The whole idea behind REST is to look at the way the web has worked and try and project that to the way we create our
systems. That's it. REST stands for representational state transfer, and it was written by a guy called Roy Fielding in his dissertation. It's based on how the web works. So what Roy did said, you know,
the web has offered us a whole bunch of things, all the ones that I've mentioned, among other things. If I were to somehow create my systems so that they offer me these same things, that would be pretty awesome. How do I go about doing that? How can I leverage everything that the web has offered in my systems? And that's when he came up with a series of constraints.
And he realized that the way the web works requires specific constraints to be put in place. And if we follow these constraints, then we achieve what the web achieves. So if we can somehow take our system design and
put in a series of constraints, a bay, a series of constraints, we can potentially obtain the same thing the web has, which is in common with a lot of things that we try and accomplish when we create systems. So REST is nothing more than a series of constraints.
REST is not an HTTP API, right? There are many systems, many systems out there that have RESTful interfaces, yes, and interfaces. More like RESTless,
because they are not RESTful. Now, can you call them REST interfaces? Sure. You can call a dog a pony as well. But what are you accomplishing? It's not about being dogmatic. It's not about saying, oh you idiot, it doesn't matter that you call that a REST and it's not REST, don't get so worked up.
It is. It does matter because we should call things for what they are. Among other reasons is because people that are not familiar with the concepts will just get confused. And then they'll look at your system and they'll say, where are all these promises that you promised me?
It's not there and this is a RESTful system. And you're like, well, no, actually it's not. So that's why you don't have those things. Right? So it's very important to distinguish a RESTful system from an HTTP API, which is what the vast majority of systems out there are. We've even been guilty of that. We have a product at JetBrains, which we say it's got a RESTful API.
It does not. And we're pushing to change it or at least rename it. Okay, so let's not distinguish. I mean, let's distinguish the two. HTTP API means I have a interface where you can use HTTP to talk to me. That's it. Nothing more. So, Leonard Richardson
has a book that I'll recommend at the end of this talk. He came up with this idea of the Richardson maturity model, which basically defines different levels of RESTfulness. But I say RESTfulness in quotes because it's not REST.
According to Roy, the only true REST is level 3. That is when you call a RESTful system. Everything below that is not REST. But this is a good system in order to allow you to understand what a RESTful system is. And we build up on this to get to what REST is.
So it's very good to look at what we have actually and build up on it to see where we want to go. Level 0 is POCs or plain old XML. And this is what the vast majority of systems are. I have an HTTP endpoint and I post some information. Normally, I do it in XML.
Where I define the method call, I define the parameters and I send that over. That's it. That's all I have. And every single operation that I want to perform is a post and the XML contains the operation. So if I want to get a list of customers, I would say get list customers and send it in that package and do a post. If I say add a new customer, the operation would be add new customer. Here are the parameters, post.
That's level 0. And that's what a lot of systems are. Then we go to level 1, which we start to identify this concept of resource, which is fundamental to REST. And we'll cover it a little bit more in detail in a minute.
But we get to level 1 and here we start to say, okay, well now I'm not going to have kind of like just one single endpoint. I'll start to have more endpoints. But I still kind of focus on single verbs. But I start to try and create a distinguishment between what these different endpoints are.
I don't necessarily identify them as what a resource is, which we'll see, but they can even be operations, etc. Then we get to level 2. And this is where everyone says, oh, I've reached RESTfulness. This is the majority of systems out there that say I'm REST. And this basically is, oh, I see
HTTP has verbs. Let me use them. Get, put, post, delete, options, head. Right. So now when I want to get a customer, I use get. When I want to create a customer, I use post. When I want to edit a customer, I use put. And I've accomplished REST. No, you've just saved yourself some trouble by not defining operations.
But you haven't accomplished REST. Now I keep talking about HTTP and I'll get to a moment later on about if HTTP is important in REST or not. Level 3, which is REST, is hypermedia. That is the fundamental pillar of REST,
which gives us a lot of the benefits that we're talking about. About scalability, about maintainability, about flexibility, all the abilities you think of, it's at level 3. Okay, we'll start at level 2. We're going to start at where we assume that we have verbs and we have resources.
So what is a resource? Anything can be a resource. Anything. A customer can be a resource. A customer list can be a resource.
An employee can be a resource. An order can be a resource. A shipping requirement can be a resource. A shipping dispatch can be a resource. A lot of times when people start to look at this REST thing and we talk about resources, the first problem that comes to mind is, okay,
I understand a customer is a resource. I understand an order is a resource. What about things that aren't entities? And we'll see how we deal with that. A resource is identified with a URI, uniquely identifies a single resource, a URL.
Then we have representation of resources. So if I access a URL and I say, give me back customer 25 or give me back customer Joe, I can send that customer back using a text HTML, which is the
page that you see when you go to your website. But I can say, you know what, give me back that customer in application JSON or give me back that customer in XML. So I can have different representations of a customer. I could even request a customer as an image and it would
give me back the picture of the customer. So we have resources and we have representation of resources. So one resource has multiple representations. When we want to request these different representations, we can do it in various ways. And there is no one way that is rest
and the other way that is not rest. It's just who is doing it. And you can provide one way, the other way, both ways to provide more flexibility. So if I'm in a browser as a human being, I go and I type customer slash 25 dot JSON and I can get back a JSON representation of my customer.
What use would it be to me as a user? Very little. As a developer it would make more sense because people want to see web pages when they see customers, not JSON. And I can request that using different URIs or I can request it using this thing called
content negotiation. Content negotiation is basically a header in HTTP that the browser sends to server and says give me back this resource in this media format. So by default when you make
a request to a URL, by default the browser says give me back a resource in text slash HTML. And the server says here you go. And if you don't have text HTML you can supply a different format as well. So you can say give me back in text HTML and if you don't have text HTML give me back application XML and if you don't have application XML give me back application JSON.
And the server will say I have text HTML here you go. If it didn't have it it would say but I do have application XML. I'll give you back that. That is why it's called negotiation because it negotiates different possibilities and it has fallback options. So we can request
a resource in a different representation with either of the two ways. Nothing is more rest than the other. We can even notice here I have a URL that is pointing to an article that is in Spanish. I can use that or I can use the accept language which is another header in HTTP
which allows me to specify the language. Okay here is one of the most important things of REST apart from hypermedia which this is where we start to see the benefit. REST is based on a
resource. So what I can do in REST is limited. I have a resource, I have a representation of the resource and what I can do with this is limited. I can create a resource, I can delete a resource, I can update a resource, I can see a resource. That's it. I can't do more. Okay and there's two important
things here. First of all, does this mean that REST is specific to HTTP? No, it does not. It just says these were the verbs that were in HTTP because this was based off of how HTTP
works and these are the constraints. The other important thing is what happens when I can't identify something as a REST. So here is a typical scenario that you have when you're trying to do something in a RESTful way. You say to me, oh you said I can create everything as a resource. Fine,
I will create a customer as a resource, right? And on that customer all I can do is create it, delete it, update it or read it. I can create an order as a resource and all I can do with that order is what? Create, read, update, delete. How do I manage an operation which is
ship order if there is no verb which is ship order? It's how you think about it. Anything can be a resource. So instead of me having an order and an operation which is ship order, what would I have? I would have a resource which is order shipment and then I
would create an order shipment and I could update that order shipment and I can cancel that order shipment. So it's just how you envision the resources. What is the benefit of
this constraint? Because this is one of the constraints I'm talking about. What is the benefit? Interoperability among other things. We don't have to have WSDL anymore, right? What is one of the problems with technology such as SOAP? You have this big WSDL file and you have to figure out the method names, the parameters, etc. Here it's like that's all you can do.
So as soon as you talk to a restful system, you know what you can do with it, right? That's all you can do and if one system says you're not allowed to delete, it will throw back an error and say you don't delete. But you know that the operation delete is viable and you don't have to worry about defining these operations. So now you say, right, I've got
resources and I know what I can do with them and that's all I can do with them. So it makes for simplicity and it makes for interoperability. It also leverages certain things such as idempotency and safety. What that means is that
sometimes, because we all know that the network is not reliable, certain operations have to be safe. That means if I call it once or a hundred times, it doesn't make a difference. Get is one of those operations. Head is another one of those operations. If I make the call, it fails. I know that I can make another call. So as long as you comply with this idempotency and safety,
you're good to go because if the network fails, you'll just make another call. Again, complying with a constraint, gaining a benefit. Now here's one that is a lot of people
say, is REST only based on HTTP? I mean, can I only use HTTP to do a RESTful system? No, you cannot. I mean, you don't have to. It was based on how HTTP works. It doesn't mean that it only was valid on HTTP. To date though, I don't know of any other system that is RESTful that
does not use HTTP, right? And at this point, Roy Fielding does say that you have to remain pure and not use anything specific to HTTP. But there are certain abstractions that don't make sense. How many of you use an ORM? Okay, nhibernate, Entity Framework.
How many of you have made a repository pattern over Entity Framework? How many of you have regretted it? How many of you have swapped out Entity Framework for
nhibernate or nhibernate for Entity Framework? So we create these abstractions that hide very important and useful
technology and usefulness that the system has, in case one day we have to swap it out. There are times that abstraction doesn't make sense. And I think that when we're creating RESTful system, which the majority are on HTTP, there are certain things we have to leverage
of the platform we're on, the framework we're on, the protocol we're on. And in this case, it's HTTP, right? And HTTP is not a transport protocol. It is an application protocol, which is different. People think about HTTP as if it was TCP. It is not TCP. It is a very
rich protocol that has headers, bodies, structure. It knows about different fields. It knows about operations. It has status codes. And yet we don't leverage these things. And this is important, and this is one of the distinctions that I make when I talk about why we shouldn't think about Web API and MVC separately. This is what you normally see in applications, right?
If everything is okay, send back HTTP status code 200. If it is not, send back a 500. I mean, the number of times that you see applications that any error is thrown back as a 500. Internal server error, right? It's kind of the same as the exceptions we do in our code.
Well, if it also goes okay, does this. If not, just try catch and just do whatever. Don't distinguish type of exception. These are all the status codes that HTTP has. 200 is okay. 201 means I've created a new resource. It knows what a resource is. It
has the concept of a resource. 202 is async operations. Do you know what that means? One of the myths of RESTful systems is I cannot create asynchronous calls. Yes, you can. You fire a request, and if it's asynchronous, you send back a 202 with a content header saying,
pull me here to find out how this is going. And then the client pulls you in five minutes. But inherently, it knows about asynchronous operations. Resources that have moved, resources that have been found, not found, bad requests. That is,
you made a really bad request to my resource. You tried to do something you shouldn't. Unauthorized, I don't have permission. Forbidden, not found. Even conflicts. I've updated a resource. Someone else has updated a resource. There's been a conflict. And all these status codes exist.
And all these status codes are similar to the way we require applications to act. And yet we don't leverage it. We just say 200 or 500. So then the question is, oh, wait, how do I send back error information in a RESTful system? You use the status codes.
And in fact, these status codes are being enhanced now to provide more. Right. Resources, representation, uniform set of operations, and we have these things called status codes. But that's enough, is not enough to create applications. Why? Because among other things, applications need state. Now remember I said the RESTful system should be
scalable. If you have one server and everything is going to that server, and you're making requests to that server and you're using the memory of that server, is that going to be scalable? No. So now we have server farms, right? And we have cookies. Now we've got a problem with
cookies, right? Now we have to have server affinity. The cookies have to remain to the same server. So now when a request comes in, it always goes to the same server. And we distribute requests with a load balancer among multiple servers. And these are all problems of scalability. Why? Because we continuously constantly try and store state on the server.
And there are other ways to store state. And this is one of the powerful constraints of REST, which give it flexibility and scalability. It gives it scalability because if I say to you, in REST you don't store any state on the server, already you've gained some scalability.
Flexibility? Why? We'll see. HATIOS is the ultimate REST. That is the level we have to reach, which stands for Hypermedia as the Engine of Application State. Awesome acronym. Does anybody
know what that means? No, they couldn't just call it Hypermedia. They called it Hypermedia as the Engine of Application State. What's this? I gotta wake you guys up. Come on, respond to me. Who said that? Well done. You have won a Resharpalizer. When you go to Amazon,
you see a website, right? How many of you have seen the first version of Amazon like five, six, 10 years ago? Has it evolved? Yeah. When Amazon evolves the website, do they call you
and say, Hey, we've evolved the website. Do you want to learn how the new website works? Do they? But you figure it out, right? Why? You got a page, you got links, you go to those links, you figure out what you can do. You go to a website that's got links, you figure out what
you can do. You drive the flow. You say, Oh, I can go here, now I can go here, now I can go here, now I can go here, right? I can go to the shopping cart and I can check out information. And before going to the shopping cart, I was here. As humans, we don't need a manual. We don't need to someone tell us what we can do in each state of the application.
We figure it out. We discover it by looking at it. So these links and the forms provide us with the flow through the program. Provide us discoverability through the program.
They provide us with a flow of decoupling a state. As side effects, we get scalability. Why? What am I saying here? Take this same concept of links where I have a form
and I can click on those links as a human being, take that same concept of links and forms and now say one process can talk to another process in exactly the same way. So I have resources. I have representation of resources. I have operations I can do on those
resources. And now what I'm going to add are links. Every time you make a request with a get, I will send you back some information and I'll include some links. Every time you make a request with a post, I can send you some information and I can send you a form as well. And I can say, fill out this form. And I'm going to send that back to you. You being the program,
the application, the service that is talking to me. And you as that service are going to take that response and you're going to parse it and you're going to say, oh look, there are links here. Oh look, there's a form here. I can fill this out. I can go here. It's not complicated.
It's taking the same concept of how the web works from human to machine and getting machine to machine to talk the same way. So now when I log into a site and I go to the first page and now I am the machine and I make this request to a resource and that resource is returned to me and that resource returns to me four links. What has that resource told me? What I can do,
right? What has that resource also given me? Control of the state because now the client knows what state it's in. The server no longer has to maintain the state.
The client knows now that it can go to these four links. But it's also given me flexibility. How? Because if tomorrow the service decides to add a fifth link, will it break me? If my, the way I talk to a RESTful service is, oh, here's some links. Oh, there's a new one. I
don't know what to do with this. I'll send an email out to the system administrator and say, the service that you're talking to has just provided a new URL. This is it. Here's a link with information about what this URL contains, what you want to do with it. Do you want to
adapt your system to use it? If you do, you know you've got to do it in the next iteration. If you don't, we haven't broken everything. Versus SOAP and service contracts, we've just blown things up and we've got to make sure that all the clients are using the same version at the same time and everything's updated at the same time. Here we provide flexibility. The server is saying, this is where you can go. This is what you can do.
And it's pushing that state over to the client. That is REST. That is REST. And if you don't have HATEOs, if you don't use hypermedia, you don't get this benefit. So when people implement RESTful systems that just use HTTP and just use resources and representations, they're like,
and what? What benefit did I get out of this? Not much. Where is all the RESTful promise? It's not there because you didn't do it right. You just called it a RESTful system. How do we define these links? Well, exactly the same. We define web pages.
Yes, you can use HTML. Is it a good idea? Maybe not. Depends. People use classes to designate concepts, et cetera. You can use formats that you define yourself. You can use another format which is called Atom, Atom Publishing. Atom Publishing has information about a link, who published it, when it was published, where to go from, et cetera, et cetera.
Or you can create your own custom formats where you say, instead of me giving back application JSON or application XML, I'll give back application slash VND, which stands for vendor, my company, the domain plus XML. Do I have to have different formats for every domain in my company? No, you define that. I can have all my services inside my entire company
under one hypermedia format. Does it make sense? A lot of times it doesn't. Does it make sense to break it up based on the domain? Yes, it makes sense based on the complexity of the domain. If it justifies it for itself, you break it up. You define this. Do you need to register this with any organization in order for it to work? No. Is it recommended?
Yes. How public is your service? Is your service only going to talk to three different people? Yes. Does it matter if you register it? No. It depends, right? Anytime you don't know something, you just say it depends. So with program flow, we start to get,
we're sorry, with hypermedia, we start to get program flow. And one of the things we do, for instance, is a typical operation here is actually that is wrong. Let me just do a quick refactoring. I do post order and I send some information.
The HTTP response code, which we just saw, to a new resource being created is what? 201. So it says created. Why post? Well, normally post is identified with an operation where the URL, the resource you're pointing to is not known. When you create a new resource, often
that is generated on the server side. Think, for example, I add a new order and the order number is generated from the service. So as a client, how do I know what I just generated? You can actually use a link to define it, but there is also a header in HTTP, which is called location. And what location does is give you back the location of the new resource you just created.
And now you have that resource. And now you can say, now with this resource, I can go and do this operation or I can do that operation with it. The server creates the resource, sends you back links, sends you back enough information for you to know where to go next.
This is a custom format. This is taken from the book Rest in Practice, which is also on the recommended list. You can find this online as well. It's a system called Restbox by Ian and Jim, authors of the book, where they explain to you the flow of ordering
coffee through a RESTful system. So I create some coffee. It gives me back the information about the type of coffee I've created. And then it says the status is expected payment. And here is the link you have to click on, click the process call to make the next step. So the state is being pushed to the client. And if tomorrow, as in their example, a new
offer comes out that you get a free donut, you just add a link and say, offer free donut, click this. And if someone doesn't click it, if some process doesn't know about that, nothing happens. So knowing this, can we leverage ASP.NET as a RESTful platform?
Now, here is the part about, do I need web API and ASP.NET MVC? Until recently, web API, if you've not heard about it, was under this umbrella of WCF. WCF normally is an acronym
with, oh my God, XML. So they maybe thought it might be better to put it under some other product name, which is ASP.NET MVC, which has kind of a good reputation. Of course, that leads us to what Microsoft always leads us. It's like, okay, now what? Which one should I choose? And the patterns described on the web are,
oh, when you want an API, so RESTful API, use web API. And then for your user interface, use ASP.NET MVC. And if you came to my talk this morning, I kind of call that bullshit, because my user interface is nothing more than one usage of my API. Why do I need to separate
this out? To what benefit? Use either web API or use ASP.NET MVC. Why should I separate it out? All you're doing by separating it out is adding more work to yourself, because at some point, these two APIs are going to call the same kind of logic,
same kind of business, same kind of pattern. At some point, you're going to duplicate work. To what end? So I'm not for that. You can use web API. It has content negotiation. It has routing. It's more resource oriented. It embraces request response, which that means that basically
you've got a class which is HTTP request, HTTP response. You can get access to that in MVC. With MVC, you have routing and you have a user interface. So with this guy, you don't have a contrib, sorry, web API contrib, which provides you a view engine. With this one, you don't have content negotiation. But hopefully now in the demos that come from now to the end
of this talk, I will show you how easy it is to extend MVC to try and do RESTful systems without having to do web API. And both offer extensibility. So you don't need the two heads
and definitely not the two controllers. Everyone here is familiar with ASP.NET MVC? Who's not? Okay, who is? Right. Just a quick recap. A request comes in. We have the concept of controllers. Controllers call models, models, sorry, controllers call actions,
actions call models, models give back data, whatever. That's the URL controller class, class action, action method, right? There we have a problem. Actions are operations. They're not resources. Do you see the mismatch? I have, if I put customer controller there,
I now have to define operations on that customer. In REST, you don't define operations on a customer. The operations are known, right? It's put, get. So this is operation oriented versus REST is resource oriented. But we have these things called filters.
And these filters, if you're not familiar with, are going to be very useful. In MVC, it's one of the best accessibility points. You got on result, on action executed, executing, executed, result executing, result executed. This happens before an action is executed. The next one happens after an action is executed. The result happens before the result
is returned. And the on result executed happens after it's returned. And we can leverage this for a lot of things. I'll show you how. Verb routine, let's switch over to code. Are you sick of PowerPoint? Are you sick of me? Oh, that's cruel. I'm losing my voice here
because I feel that the microphone isn't loud enough. Is it loud enough? Well, you could tell me and I can lower my voice. I'm really, it's hurting here, people. So I'm just going to push
the limit here. I have 2002 with an internal build of ReSharper. All hell can break loose. My mom always says, if you're going to fail, fail with style. So here is my code.
Now everybody understands the mismatch, no? I have customer controller where I normally define methods and I have resources. There's a mismatch. So how can I bridge this mismatch? Well, here is one example and don't just have faith in me. You won't have to do this ever.
Here's an example. What this does basically is says I have a customer controller and I have details. I have delete, I have update, I have create, et cetera. And what I want to do is
I don't want to have to call. When I wanted to do a delete of a customer, I don't want to say customer delete 25. Right? I don't want that. What I want to do is customer 25, but instead of a get, I want to do a delete. That's what I'm trying to do.
Now in MVC, what you can do, and in fact, in the first preview, you had to actually do this and then they made it the action name to be convention based on the method name. You can define an action name. So here, what I'm saying is that every single action is called the same, which is a rest action. And then each one has different verbs. So this
one will only work with a get. This one will only work with a delete. What does this single action name provide me? Well, I create a root where I say rest roots, customer ID, and then all of them are mapped to action rest action. So when the root processing comes in,
it's always going to call rest action. When it goes to execute rest action, it says, I've got five methods of rest action. Which one do I execute? MVC can discriminate based on the verb and then it will just do the appropriate one. Right? How many of you like this solution? I'm hoping nobody. That is not a solution I want to do.
Right? I'll show you another solution, which also I hope nobody likes that much.
In this case, I have index, details, delete, update, create, and you see that I've not decorated anything with any verb. Right? Now let's go to the routing table. And what I have here is customer create, customer details, customer delete, customer update,
etc. So all of these are going to go to the different roots, but I do have a routing constraint over here. And what this does is basically it makes sure that the request comes in is mapped to the method that I say is allowed.
Okay? Who likes this approach? Why don't you like this approach? Pardon? Too much configuration. And the other approach is too much repeating yourself. Right? Good. We'll come back to another way of doing this later. But that is how you map resources to,
that is how you map operations to resources with MVC. Okay? Content negotiation. A lot of times when I see people using rec or creating HTTP or RESTful systems, I see a method which is customer controller
method details. And then I see another one, which is customer controller and the method details JSON. Has anyone ever done that? So you have one method that gives you back
a customer view and another one that gives you back a customer in JSON. That's horrible, right? It's also horrible to have an if inside a single method telling you which format to give back. So what do we do here? This is content negotiation.
I do action result get, get the customer by ID and I do return view. And if I call that from a browser, it will return to me a customer HTML page. If I call that from Fiddler or a process, it will also give me back an HTML page. If in the call I say give me back
customer25.json, it will give me back that in JSON. But that is transparent and it's not
transparent. So this is a very hacky solution. Normally you wouldn't do it like this, but it's just for simplicity sake. What this does is basically say you can request different
formats, different representations for me based on the URL, based on the content type, etc. So it provides all three options, right? The content header. First it sees if the URL has any dot extension equals JSON or based on the query string,
customer query exclamation URL, sorry format equals JSON or the accept headers. So it first sees if a request is being made that requires a special format. If it does, then it gets the extensions and it passes it to encode data. What is encode data? All this does
is encode the data based on the format I've requested. So here I'm just using a JavaScript serializer. If I want XML, I'll use an XML serializer. So all this is actually is nothing more than creating an action filter attribute and overriding the on action executed.
When an action is executed, I can check for a specific type of view result, see if it has a model. If it has a model, I'll see if it's requested a special format. If it has, I'll encode it in that special format and send it back. I do it once and it applies
to everything. Again, you wouldn't have to have to do this manually either, but it's very simple to do. It's leveraging the filters. So now I have content negotiation system-wide with no effort, one filter. Another thing that I said you need in RESTful systems or in
HTTP-based systems is status codes. Out of the box ASP.NET MVC doesn't ship with status
codes. And here's where with a web API, they make a big deal. Oh, you have access to the creating a customer, right? So I created a new customer. I save it to the repository. And again, there are some things that are hacky here, like this generate root. It's done for
simplicity, but I say generate the root and then I do new post result. So instead of doing a new view result or whatever, I do a post result. What is post? Well, post just inherits from action result and it sets the header for me. It sets the status code to 201. It sets the description and then it adds the header location, which if you remember,
I told you is required when you create a new resource. It now sends back the location of the new resource. Point being, you do this once and it's done, right? And you've abstracted away from HTTP in your code, but it's still HTTP. And it's very simple to do.
Okay, one of the things with REST is authentication. The problem with doing cookie-based authentication is that the cookie has to live on the server
normally. Depending on how you handle it, there are ways around that. But by default, forms authentication in ASP.NET MVC uses cookie authentication with the cookie on the server or stored in a server farm. That's against the constraints of REST. You can't put state on the
server. In REST, normally you can use another type of authentication which is called HTTP authentication. This is home controller. This is admin controller. And you see that I have a new attribute called HTTP auth. What is that? That just overrides, again, it inherits from
action filter attribute and overrides on action executing. And this is a simple implementation of HTTP authentication. Basically, with HTTP authentication, when you go to somewhere that's protected, it sends back a header saying authentication is required. Then the browser
pops up the dialog box requesting a username password. And what it does is send it to the server using base64 encoding where you have the username colon password. Very unsecure. That's why with HTTP authentication, you have to either use message digest or SSL. But if I execute this,
I'll show you. I can go to about us home. If I go to admin, I get the dialog box popped up. ABC, ABC. And it goes to the server and it brings down the server. So if I look at this,
what I'm doing is on action executing, which is the filter that occurs right before an action is executed, I check to see if, sorry, where am I? Yeah. I check to see if an authentication header has been sent. If it has, then I parse it, get the username and password, and I just hook on to CAS, code access security in .NET, use the same concept of generic principle,
user identity. That's it. That's the only thing I have to set. From there on, I can use all code access security, just like you do with forms authentication. It's very simple. Okay. One other thing which is important for HTTP is caching.
And this is actually very important. And I think that they don't have support for this even in web API. But I, again, point is to show you the simplicity. I'll put cache, you know, that exists in ASP.NET MVC. So you can cache a specific resource, but there's another cache
system in HTTP, which is called a conditional get. So conditional get basically says, do a get, give me back the resource, right? But if the resource is big and it hasn't changed, I don't want you to get it back. So what you can do is you can create like a hash of that resource
and send back that header and say, this is the resource hash. The client can say, oh, it hasn't changed. So I won't request it. If it has, send it back to me. And that's using the concept of modified headers and ETags. So here, what I'm doing is saying, get me a customer.
And if the customer hasn't changed, then don't give it back to me. If it has, then give it back, right? And I've put a new attribute that I've created, which is called conditional cache. And if we click on this, again, using on action executed, what I do is I get the model, because I'm assuming that this is a view result and has a model. Obviously the error checkings
would need to go in place here. And I say, okay, generate the ETag for the model. So this is just taking the model, serializing and generating a hash, some whatever, you can base that on whatever you want. Then I check to see if an incoming ETag has been sent, which is set to if non-match. So basically what the client request is doing, the browser
is doing is saying if non-match this value. So if it doesn't match this value, send it back to me. I see if that value has been sent. If it has, I compare the ETag with the incoming tag. If it's the same, then I send back an HTTP status code result saying three or four, not modified.
If it is different, or if it is blank, because it's never been sent, I then add a header called ETag. Done. Conditional get implemented with a simple filter. But when you look at RESTful systems and you look at conditional gets, which is very good for scalability, you might get scared and say, oh,
NSP.net MVC doesn't support this. Done in four lines of code, right? In Vnext, you can just drag and drop it down. Oh God, you guys are so asleep, aren't you? I've mentally taken a picture of every single person that's fallen asleep, huh?
So one thing I want to mention, much of what I've shown you, and this isn't a personal pimp, okay? Much of what I have shown you is available in a project on GitHub called Easy MVC, which I haven't touched for two years. That's why I'm not trying to pimp my own project, okay?
But all the content negotiation, all the routing, all that is done. In fact, with Easy MVC, all you need to do is create a new project and follow some conventions. Remember how I did mapping with the verbs? With Easy MVC, you don't need to do that anymore. Okay, let me just show you a quick example. And this, again, this is based on what,
showing you the simplicity. So let's go to projects, Easy MVC. So this is an example using Easy MVC. This is a sample app. If you look at my controller,
customer controller, this one has gets, et cetera. Employee controller has list and details, okay? And my MVC application also has no routing. All it does, it says, this is from Easy MVC,
it says root generator, generate roots from assembly. And this uses some default conventions that says map action list to verb get on root of the controller. Map action delete to put, sorry, to delete on root controller root with an ID. So basically it's using convention.
As long as you stick to those conventions, you don't have to define any verbs or anything. And much the same with content negotiation. It automatically injects it in, okay? Again, point is the simplicity, not to, for you to use this. Oh, wait a minute. Let me see
where I am. We're summing up. Don't worry. Okay. Just quickly, client side. Oh, hypermedia controls, neither REST, neither Web API nor MVC provide anything in hypermedia
controls. So Atom and all that, you got to do yourself, either technology you use. Client side. When talking to this, you can use Ajax if you're from a browser, outside of a browser to implement the client side interaction with a RESTful service. You can use any HTTP library, be it web request, be it easy HTTP, be it rest sharp,
anything you want, you can use. Okay? When you're doing it from a web browser, there is no delete verb in the form and that you can override. You have to simulate, you can do that with a hidden field or use an extra header, which is X HTTP method override and say that this is an actual delete. That's one shortcoming when using it from the
browser. Okay. Takeaways. REST is a series of constraints. If you follow these constraints, you gain a series of advantages. If you don't follow them, you won't gain those benefits. If you do up to level two, you won't get the benefits of REST. You'll just have an HTTP API. Call it for what it is. It's fine. There are no issues with having an HTTP API,
but REST does give you a lot more. It gives you flexibility to evolve your system without having to update contracts. And personally, I say embrace HTTP for what it is. You want to use one technology, use it. You want to use the other, use it. But this concept of, oh,
I'm going to separate out my API controller from my user interface for me is absolute nonsense. Okay. Recommended reading, REST for web services, Leonard Richardson, highly recommended and not very convenient name, but it's RIP, REST in practice,
by Jim Weber and Ian Robinson. Very good. This comes with Java and C-sharp examples of how to do things like the hypermedia links, forms, et cetera. This is a more gentle introduction, but it's a very good introduction. He doesn't call this, if you look up HATIOS in this book,
he doesn't refer to it as HATIOS. He refers it to connectedness. But it does still cover hypermedia in depth. So if you don't have any questions, thank you once again for being here and enjoy the rest of the show.