Implementing an API in ASP.NET Web API by Shawn Wildermuth Released1 Oct 2013

Course Introduction Introduction

Welcome to the Implementing an API in ASP.NET Web API course. My name is Shawn Wildermuth with Wilder Minds. In this course we’re going to build a REST-ful API using these technologies. We’re going to walk you through step-by-step and show you the actual code as we build it, and any cases we can. We’re going to start out by showing you how to get ASP.NET Web API into a new or existing project. We’re going to show you how Routing and Controllers work. We’re going to use Dependency Injection with Web API. We’re going to show you how to Map your Entities into Models so you can return Resources from your API. We’re going to talk about managing Formatting of Results both in JSON and XML, but we are going to focus mostly in JSON. We’re going to talk about securing Web API in a variety of ways, basic authentication, token authentication in OAuth. We’re going to talk about several strategies for versioning your Web API Services. And finally, we’re going to talk about implementing other REST Constraints, like including Caching, ETags, Hypermedia, as well as HATEOAS in general. We want the course to work by showing you the actual work that’s involved. This will allow you to follow along if you like, or just view what we’re doing so you can see that it’s not overwhelming to get involved. You’re going to see me build the code, and you’re going to see the workflow in process that is required to create an API from scratch. And, hopefully, you’ll be able to make sense of how these two work together, so, you can see how they all fit together in a cohesive project to expose in API. Ready to get started? Implementing an API in ASP.NET Web API Introduction

Welcome to the first module of Implementing an API in ASP.NET Web API. My name is Shawn Wildermuth with Wilder Minds. In this module we’re going to introduce you to Web API. We’re going to start and talk briefly about creating web services with REST and how to be pragmatic about that. If you have viewed my other course on Web API design, this is a link to that course. We are going to be talking about some of those same central topics, and you’ll get more out of this course if you’ve viewed my other course, but it is not a requirement. Next, we’re going to be talking about why we would choose to build an API using ASP.NET Web API. We’ll then show you how to get Web API into your project, or have you start a new project with Web API. We’re going to build a controller. We’re going to talk about serialization in Web API. A bit about dependency injection. Talk about Models versus Entities and how they relate to REST and Web API. And finally, introduce you to Routing and Parameter Mapping in Web API. Let’s get started. Pragmatic REST

When you’re building APIs on the Web, there are several ways you can build APIs on the Web. These include HTTP/RPC, and what this means is using HTTP in Remote Procedure Call to call into things, like Methods, across the Web. The verbs themselves are included in the APIs, like Get Customers, Insert Invoice, Delete Customer, and that each of these endpoints ends up being a separate URI. So, for each of the types of operations you’re doing, you’re going to expose a new URI. This is more of the old school model of how you would expose an API on the web. Another Model is what is often called these days REST-ful. It includes the idea of URI endpoints that point to functionality, but they’re using resource URIs instead. They’re leveraging HTTP verbs so that if you’re going against, let’s say a customer endpoint, that using Get against that endpoint is going to retrieve data, doing a Post against that endpoint is going to insert new data, etc. It also includes concepts, like a Stateless Server and Content Negotiation, so that the caller can specify what kind of data they want, and that the server itself is stateless. There’s no notion of we’re within a single call on a server so that they can be scaled out better. Lastly is this whole notion of something called HATEOAS, or Hypermedia as the Engine of Application State. A horrific acronym, but the idea here is to extend the REST-based interfaces to include things like relationships, and what is called hypermedia, so that the content of what you’re getting back will describe the kinds of things you can do with it. So, if you get a customer back, there may be a link to it that says this is the actual customer, this is how you add an invoice for this customer, this is how you check the balance for a customer. It’s going to include links to allow you to be more self-describing. We’re going to cover REST-ful and HATEOAS in this course, but most of the course is going to be about this REST-fullness. When it comes to REST, there’re a lot of different opinions out there, and they can be very entrenched in their opinions. I prefer the approach of what I like to call pragmatic REST. REST is just a useful set of rules, but they tend to be dogmatic. The list of what makes an API truly RESTful can tend to bog down the pragmatic job of exposing an API that users and customers actually need. Developers end up spending a lot of their time making sure they fit into the religion of REST instead of actually getting the job done they need to get done. At the end of the day an API has to serve your users and customers, not serve the people who are going to tell you whether it’s truly RESTful or not RESTful. I don’t what to take this concept of REST itself and just throw it out. I want to take what’s really good about it, and in the situations where you can be completely RESTful, do that. But, if you need to break the rules to be pragmatic, I propose you do that. This also means doing just enough REST to get the job done. I wouldn’t worry about heading to your local user group, or hearing at a conference that one of the 6 rules, or one of the 12 rules that someone has dictated, is what REST actually is, that you’re breaking those rules. But, if you’re getting the job done, and really adhering to the benefits of REST, I think that’s good enough. Why ASP.NET Web API

So, if you’re viewing this course, you are probably looking for the way to build these REST Services in .NET themselves. And, let’s talk about some different approaches that are out there in .NET for building these services, and then let’s hone on why Web API I think meets the requirements best. You have choices in .NET. This includes ASP.NET WCF. This where you’re going to take the existing SOAP-based stack the WCF exposes, and annotate it in a way to allow JSON objects, or non-SOAP objects, to be returned from the those sorts of services. Configuration in WCF in general can be a headache, and this is continued whether you’re using REST with a WCF stack or not. Another choice is to use ASP.NET MVC, and this would be extending the controller model to return data that is in JSON formatter to accept Posts, Puts, Deletes, and other verbs in your controllers. You can certainly do this, and there’re a lot of applications out there that do this. This can be difficult because often you’re trying to match the names of verbs inside of Action methods in ASP.NET MVC, and you tend to have collisions with the same method, having the same number of parameters, even though you’re really specifying one as a Get, and one as a Put, and one as a Post, etc., so it can become a little overzealous. And, again, having to add attributes at every level to specify, oh, this is a Post, this is a Put, this is a Delete, this is a Get, can be cumbersome. The other choice you can make is ASP.NET Web API, and this was designed specifically for this use-case. It’s more natural to implement REST because the verbs are directly mapped to Methods. So, the Method name of Get actually does a Get, the Method name of Put does a Put, Post does a Post, etc., and it takes these natural conventions that make more sense for exposing each of the controllers that are specific to REST-based APIs. They encourage the separation of what you’re mapping and what you’re building. So, instead of having to use attributes to say, this is magically where a Post or a Put goes, you can have the controller be more self-describing so that you know a Post is a Post and a Get is a Get. It also allows you to host outside of IIS, and in some cases being able to build these sorts of services that you’re using inside of an enterprise, or for a custom solution, like drop shipping machines. This can be really useful for allowing you to host it both in IIS, as well as self-hosting it, or even in other web servers. The one caveat here is ASP.NET Web API does require .NET 4 or above, and so if you’re still using ASP.NET 3.0, 3.5, or even back to 2.0, this is a limiting factor, and you may want to choose one of the other choices. So let’s see how Web API works. What are We Building?

So, in getting started with Web API, I wanted to set some ground rules, so you understand what we’re building and how we’re building it. First of all, we’re building a Whole API. I’m going to be building as much of it in front of you as I can, and where I don’t actually build the code in front of you, I’ll talk to you about it very specifically about that we’ve added this in, and what way. But, we’re only building the API. We’re not building the database, or the data layer in this course. We’re going to be using a prebuilt one using the Entity framework, but all the concepts we’re going to talk about are going to be true, whether you’re using Graven, or Couch, or SQL Server, or raw ADO.NET. It doesn’t matter how you’re getting your data, the concepts for building the API itself are going to be the same. We’re not building a website to support the API either. That’s going to be a separate operation, and the same sort of standard web development techniques you can see in other courses, both mine and others here in Pluralsight. We’re simply about building that API. And we’re not building the client side code. You’re not going to see us build JavaScript or other clients to interact with the API. We’re going to be doing some testing interactively to show you things that work with tools like the Browser, or things like Fiddler, in order to show the API working, but we’re not going to build that code itself. We’re trying to stay focused on just building the code that is required to expose in API. What we’re doing requires Visual Studio 2010 and above. We’re going to be using Visual Studio 2012, but it will work with older versions of Visual Studio, as well as newer versions of Visual Studio. As at the writing of this course, Visual Studio 2013 is out as a preview, but because it isn’t done, we’ve decided to use 2012 as the platform. If you do use Visual Studio 2010, you will probably have to manually install ASP.NET MVC 4 in order to get the ability to include Web API into your projects. Again, Web API requires .NET 4 and above, so any of the techniques about adding it to your existing project you’re going to see aren’t going to work if you’re not already using .NET 4 or above. .NET 4.5 added support for async. We’re not going to be doing a lot with async, but understanding that you’ll get the most out of Web API if you are using .NET 4.5 or above. And before we get started, I do want to talk a little bit about the data we’re going to be working with. The shape of the data we’re looking at is really three-fold. There’re three types of data we’re going to be dealing with. We have the notion of a Food, and this is a description of a certain food, might it be butter, or milk, or steak, and then a Measure of that food, and each food can have multiple measures. So, we might have a pat of butter or a pound of butter. We may have 1 ounce of steak, or we may have an 8-ounce steak. So that within each food there’s going to be different measures that have nutritional information; how many calories, how much protein, etc. For individual users, we’re going to have the notion of a Diary, and a diary is what food I’m eating on a particular day. You can probably see where this is going, where we’re going to building an API that allows people to count calories. And in the Diary itself, we just have who owns it, and what the current date is. Within that Diary, there’s going to be one or more diary entries, and each of these diary entries has a relationship to a food and a measure within that food, so that a diary entry is going to say, I had three pats of butter. I had one 8 ounce glass of milk, whatever it may be, so that we can, in the diary, compute what their nutritional information is for the day. Those four tables themselves are put together to represent the data that we’re going to be exposing through the API. We’ve also got two sets of data that are about security that we’re getting to in module three. The first is ApiUser. This is someone who has registered with our service in order to use the API, and so we have an AppId, and a secret that that the API user has been handed that they’re going to use to authenticate into our system. Then we have this notion of AuthTokens, and these are tokens that are handed out as API users request a token with a certain expiration. So, they can use a token for so many method calls until the expiration hits, and then they’re going to have to request a new token. But again, we’ll talk about how that works, but those two pieces of data are specific to security, whereas Food, Measure, Diary, and DiaryEntries are about the actual data we’re going to expose through our fairly simple API. Let’s get building. Creating A New Web API Project

So, let’s start by getting Web API in a new project. I’m here in Visual Studio 2012, and I’m going to create a New Project. In this case, I’m going to just create an ASP.NET MVC 4 Web Application. There isn’t a project specifically for Web API. It’s a subproject of ASP.NET MVC 4. And I’m just going to call it NewWebAPI. And, when we get here to the Wizard in Visual Studio 2012, it’ll be similar in 2010. In 2013 they’ve changed this up a bit, but you’ll be able to get the sense of what you want. As we can create different kinds of web applications, Internet Applications, Web API Applications, which is just a raw Web API project, though, some of these other projects are going to include Web API, or at least include the ability to add Web API to them. We’ll talk about that in a minute. But, I’m going to go ahead and just create it as a straight Web API project. Let’s explore this a little bit so we can see some of the base concepts of Web API in case you’re not familiar with them already. In the Global.asax file, there’s going to be an Application Start section, and this is whenever your application is started up. This isn’t once per request, but once per startup of the application, depending on how you have IIS configured, or, even Azure configured. This may be more often than you might imagine, but it is not once in every request. And at this point, there’s a number of configuration that happens. There’s configuration for Areas, for Filters, for Routes, for MVC Routes, for Bundling. What we’re interested in is this WebApiConfig registration. So, I’m going to navigate over to this by hitting F12, if you’re not familiar with the shortcut. Now, this is going to take us to a class that actually exists inside the App Start Directory, WebApiConfig, and this contains one, and only one static method called Register, that’s going to do the startup configuration. The first thing it does is configurate default route for Web API, and this route is a pattern match. When someone hits the server with a URI, it’s going to attempt to match these against these routes. ASP.NET MVC can have their own routes. These are in addition to those routes. It’s pretty commonplace for these routes to start with api/, and then have whatever the controller name is, and optionally what the ID inside that controller is. Now what this base project has done is created a controller for us called ValuesController. If you’re familiar with ASP.NET MVC, this may look a little familiar, but this is an API controller instead of a plain-old controller. This is a Web API specific controller that knows that we want to do this convention-based mapping. So, the name of the controller is called Values, and so what the Web API configuration is going to do, let’s go back there, is if we come in to api/Values, it’s going to look for the controller called ValuesController. It’s going to take whatever the name of the controller we specify here and match it to a controller in the project that has a name, plus the name Controller. Again, this is by convention. We don’t have to set up configuration for this. Let’s go ahead and run this in the browser briefly. And you’ll see during this course I’m going to use Firefox as the browser, because I can use Firebug to do some interesting things. We’ll also use a tool called Fiddler in order to more easily do things like Post, Put, Patch, Delete to the server. But for simple Gets, this is a good place to start. So I go up to the Address Bar and just type api/values. This is going to call into the controller for Values and issue a Get. In the HTTP stack, Get is one of the verbs you can issue. In browsers typically, issue Get in order to get information, it’s the most common verb. When you go to a website, it issues a Get to that website for that page you’re looking for, and then the server returns the information that is the value of the page. The same thing with Web API here. In fact, if we go ahead and look at the ValuesController, there is a Get method that returns a list of strings, or an enumerable collection of strings, and we can see here that it’s mapping it to this exact method, because we’re issuing a Get. and we’re issuing a Get with no additional parameters. Again, it’s just values, so it knows it’s is an empty call to Get. So, if we change this to add a new value, and reissue it, it will return the value. And this return value by default is JSON, so this is the syntax in JSON for a simple array of values. In that same way, if we look at our code, we can see that there’s an additional Get that takes an ID. This ID was specified in the configuration file as part of that route pattern. So, if the ID is specified after the controller, it is specified as a new parameter called id, and it’s optional. That’s why we could call it without it. And what it does here is just return a string called value. It returns a single instance of some object. So, we go back to the browser, and we change this to /1, we can see that value being returned. One of the things that’s not super obvious here is that whatever is being returned here is being converted into a JSON object for us, or XML in those cases, but we’ll talk about that in a minute. If we change this to just return object, we can then construct an object on the fly, and I’ll just use an anonymous type, and say name equals value, and id equals, and I’m just going to pluck in the id that we’re being passed in as part of that data. Now, when we execute values1, it’s going to return us a JSON object that is going to include the name as whatever we specified, and then the ID. This is a core idea in Web API that you’ll going to deal with and return simple return types here, and that Web API itself will figure out how to format it. What’s interesting is that we have this value that’s being sent in as the ID. In this case, it’s a 1. If we change it to a 5, it will go ahead and pass it through as a 5. But that this is implicitly an integer. It’s an integer, because by convention we’ve asked for an integer in the API. If we change this to foo, Web API is responsible for mapping the URI values into whatever values are available on the controller. It’s trying to do smart mapping between those, so you don’t have to worry about writing some sort of code that’s going to figure out how to manipulate and push these values directly into your controllers. This is all interesting, but this isn’t the real API we want to build. Let’s next talk about how to add Web API to existing projects, because that’s a much more common case. Adding Web API to an ASP.NET Project

Next, let’s talk about adding Web API to existing applications. So here I have a Visual Studio project already open. It’s called CountingKs. It’s going to be a project that we’re using to host some data that users can go ahead and create diaries, and have nutritional information, like we saw on the data model earlier in this module. So, by default, this project, when we run it, just has a very simple web page, and we’re showing some sample results from the database. We’re showing foods, and then some measures for each food. So, we’ve already got a database, and that database has some data in it that we can deal with, but we don’t have an API. That’s really the next step in what we want to do. This project not only has a typical ASP.NET MVC controller, it also has data, so we can see that there’s a second project called CountingKsData that is just an Entity Framework project that has also exposed a repository, and the repository is what we’re going to mostly be interacting with. The repository knows how to work with Entity Framework to push data, and to pull data out of the database itself. We won’t be doing much with those. We’ll assume that most of that code is already written, which it has been. You find in the samples, if you’re a Pluralsight Plus member, that we’re including the baseline project that we’re starting from this with. So, if you want to build this along with me, you can go ahead and make a copy of that baseline project, and then do everything we’re about to do. So, in order to use Web API, we actually have to add it to this default MVC project. We can do this by using NuGet. If you don’t already have NuGet as an add-in, you’re going to want to go to the extensions for your Visual Studio and add it as an extension. Most of you are probably already using it, so I won’t belabor what it does. And if I look for Webapi, we’re going to see the Web API Core Library, or just Microsoft ASP.NET Web API. This is the complete package for what you’re going to want to add it to an existing website. So, I’m just going to press Install, and it’s going to resolve a number of dependencies to bring them in, and I will have to Agree to the licenses. Now that we have Web API created, we’re going to see if we open Global.asax that we’re going to have a new line for WebApi.Register, just like the brand new project did. And, if we navigate there, we’re going to see that same registration file. One thing to note is that what you’re getting here in the adding Web API is a bit different than what you’re getting in a new Web API project. There’re some missing pieces. The new Web API project includes things like automatic documentation and such, that you may be interested in looking at how to implement, but there isn’t a NuGet package that will just stuff this into an existing project, because there’s a little too much involved for a NuGet package to just start adding a bunch of views and adding an area, and all sorts of other small intricacies. So, this is going to assume that you’re going to be adding just the API itself to your project. Another thing to note is that we have commented out this EnableQuerySupport. So, this is an optional support you can get in Web API to be able to expose an IQueryable endpoint, and the benefit to this is to allow you to expose your data from Web API as OData feeds. Now, if you’re not familiar with OData, it’s a way to allow you to more expressively query across the wire. It’s an open standard that was pioneered by Microsoft, and it’s very useful for a line of business sort-of scenarios, or where both sides are going to be somewhat Microsoft centered. There are libraries for a number of different devices and platforms, like Java, IOS, Android, etc., but I find that when I’m building an API for general consumption for developers that it tends to be a little confusing for them, and that building a standard REST-based API is what we’re going to focus on, so we’re going to leave this commented out. We’re not going to support querying over the wire. You might want to read more on what this means after you view this course, but we’re going to focus on building a standard RESTful API that returns JSON or XML. So, now let’s build our first controller. Creating Your First Controller

So, now let’s build your first API controller. Unlike our new Web API project, adding Web API through NuGet doesn’t actually add a sample controller for us. But adding a controller is pretty simple. We can just right click the Controller folder, and say Add, Controller. This will pop up a different UI that it’s going to allow you to pick what kind of controller you want. We’re going to start out with a FoodsController, but let’s talk about the different templates for a minute. The top three are the Empty MVC, MVC with read and write controllers that you might be used to if you’ve used ASP.NET MVC, but the last three are for API controllers. An Empty API controller, which is mostly what we’re going to use here. You also see a controller with automatic read and write actions against the Entity Framework. I actually don’t like what they do here, because normally I want to go through a repository to whatever the data store I’m using, so tying my controller directly to a specific storage mechanism, like Entity Framework, I’m not a big fan of. API controller with empty read and write actions will just build a Get, Put, Post, Delete method for me. I prefer to kind of go the plain-old route and write each of these as they are necessary. In many cases, I don’t want to support read and write on every sort of operation, so I would end up just deleting things I don’t want anyway. And in our FoodsController, we’re just going to want to go ahead and do a simple Get. So, let’s just get some data here. I’m going to use a repository object that we’re going to use for most of our operations, and just create a new instance of it, and called CountingKsRepository, and I’ll need to add that using statement to bring it in to our project. And it requires a context object, so I’ll go ahead and just new a new one of those up as well. (Typing) Later, we’ll talk about better ways of handling this, but for now, that should be good enough. We have a new repository that within it has the context to our data store so that it knows how to get that data. And, from the repository, I’m just going to get some results. I’m going to call repo.GetFood, AllFoods, and I’m returning a queryable here so that I can go ahead and just add some other pieces I might want, like OrderBy Description, only giving me the first 25, and then give me a List of these. Now the way that Web API works is I can just simply return the set of objects, and it will do its best to have formatted it in the way. In fact, we can just return an object, and Web API is going to look at the structure of what we’re returning and attempt to do the right thing to return the data we want. So, let’s just say return results. We’re not wrapping these, or calling JSON formatting, or XML formatting at all. These are simply going to return some raw piece of data. So, we go to our API. If you remember, we did the values when we had a ValuesController, but this time we called it our FoodsController, right? Should be able to just call that, and there is our list of 25 foods. We’re getting abalone first because we asked it to order it by the description. Our API is deciding how we want to be able to get that data. So, we’ve exposed our data directly here as JSON. What’s interesting is in the API itself, we told it to return just an object, and it looked at what would return, and tried to determine what we wanted to return for us. More commonly, we would return something like IEnumerable Food, and the reason for this is so that we can have a consistent compile time check of what we’re returning. So that we don’t get some oddity where we’ve changed the code accidentally and now we’re returning some other objects, which ends up breaking our code. There’re very few cases where you’re actually going to want to return an object and let that be okay. You can see that even though we’re now returning IEnumerable of Food, that we still get the same behavior. So next, let’s talk about how formatting is really separate from the return types we’re dealing with in the controller itself. Serialization in Web API

So let’s look at serialization in Web API, and how formatting is really separate from the controllers themselves. If we look at what we’re dealing with here, we’re returning just a collection, a simple collection of food, from the Controller method itself. How does it know that we want JSON here? Well let’s use Fiddler to figure that out. See here in Fiddler we can compose a very specific request to the server. You can see here I have our API Foods, and we’re just going to issue a plain-old GET to it. When we Execute it, it’s going to show up on the left-hand side with the result, with 200 meaning okay, and then we can actually look at what was returned. If we look at the JSON that was returned, we can see that it was actually returning JSON just like we did in the browser, and the reason it returned JSON is the way that Web API is set up, if the caller to the service doesn’t specify what kind of data it wants, it defaults back to JSON, because that’s such a common case. If we change our request over here to use a header called Accept, we’re going to tell it what kind of data we can accept. And if I say text/xml, which is in the data type for XML, and I Execute it, we can see that the Raw data that’s returned is now XML, and in XML we can see we’re getting that same data, but it’s being formatted in an XML document itself. So, it’s really up to the caller to specify what kind of formatting it wants. You can actually specify, and this is often the case, several Accepts, so I can say text/xml.application/json, and let’s say text/html. I can Accept all of these, and they’re ordered in that way so that Web API is going to take the first one that it knows how to use as a format, and when we Execute this format, it’s going to take the one that we had on the server I’ve said is our preferred format to return, and in that case, the first formatter is actually JSON. It’s going to take a look at the array of the Accept headers, and find the one that most matches our preferences on the server. So, in this case, when we Execute it, we’re going to see that it actually returns JSON again. So it is up to the caller to specify what kind of data, and in that way Web API uses these classes called formatters to figure out how to format the documents. This means you can have your own formatting. There are formatters out there for HTML, for Binary, for CSOD, etc., so you can really craft your own set of formatting, but the controllers themselves don’t end up needing to change, because all the code in the controller is for is to get what needs to be returned, and to send it back through the pipeline of Web API for the formatters to do their work. So, being able to manipulate those formatters becomes useful. For example, we have a pretty common case where what the formatter is doing for JSON is taking the name of each of those properties in the food object, which happens to have three properties, a description, an ID, and then a collection of measures that we’re not returning yet. In this case we noticed the objects that are returned are Pascal case, because in .NET our property names are Pascal case, so that they start with an initial cap, instead of being what’s called Camel cased, which is starting with a lowercase letter that is a little friendlier to people consuming it with JavaScript, which is probably going to be the majority of people that you’re going to be dealing with. So instead of having to make some change, and to model the data in a different way to get you these lowercase characters, we can really deal with the formatters themselves. Let’s go ahead and do that. If we go back to the configuration for Web API, let’s go ahead and add some code down here to get the jsonFormatter. And, we can get this by just calling the config object that was passed into Register, and we’re going to look for a specific type of formatter called a JsonMediaTypeFormatter. These formatters have this notion of media type, or the types that are coming in, so when I change the Accept header, it was specifying the different kinds of media types that we could accept. So, that means I know that there’s a JsonMediaTypeFormatter in our system built in already, and I’m going to go ahead and get the first one, which is usually the only one that is specified there. And, I’m going to make a change. I’m going to tell the formatter that when it serializes it with the serialized settings, I want to use a specific ContractResolver. Now a ContractResolver is a piece of the API, but you don’t need to get into how all these different pieces work together, but this is a really common case that you’re going to do in a majority of your projects. We’re going to change the ContractResolver to a new one that is shipped with JSON.NET called a CamelCasePropertyNamesContractResolver. This comes from the JSON.NET folks so that it knows that when it resolves each of those property names in our objects, to go ahead and make them Camel cased. By making this small change to that formatter, if we can ahead and reissue our code here, we’ll see that our property names are now Camel cased. If the description were fullDescription, it would be a small f and a capital D. It’s called Camel case because it can have humps in the middle. It has humps wherever a new logical word is, but that it’s always going to start with an initial lowercase letter. One of the reasons for making this change is that because many of your consumers of the API are going to be using JavaScript, you’re writing web pages, people are writing JavaScript plugins for things like Node, or even for some platforms in building mobile development. Camel cased return objects are going to be easier for them to use because they’re going to be more naturally looking for Camel cased objects that are common in JavaScript programming. Now that we have some basic data being returned, let’s go back to the server code and clean it up a little by introducing dependency injection. Dependency Injection

So, let’s talk about dependency injection. In our controller itself, we’re using this repository and context in creating them in order to get our data. But, we’d like to have a way to take these sorts of services and supply them to the controllers, because there’s going to be a number of different kinds of services that we’re going to need through the process of building your API, and dependency injection can simplify this quite a lot. The trick here is we would like to be able to when we construct the new FoodsController, and I use the ctor shortcut to create a constructor, I’d like to be able to specify that we want a repository, and more importantly that we actually want an interface to the repository. The reason for this is simple. We want to use the interface so that when we write tests against these controllers, that we don’t have to specify the actual CountingKs repository. That allows us to be more decoupled with the actual repository we’re working with, and it also means that later down the road, if you have some clients using certain data in certain ways, you can actually swap these out depending on which clients need what. But in our case, we really want to use it mostly to abstract it out for testing. We also don’t want to care what the repository needs to fulfill its work. The fact that we’re passing in a context as well, means that we’re further complicating this controller by having to have the knowledge that the repository requires a context object. So the trick here is we’re going to go ahead and create a new local variable called _repo that we’re going to use for all of our different methods. So, we’re going to be Pass in a repository, and then use it for whatever methods we’re going to expose on this controller. I’m going to use the little shortcut to just create a field stub for me for our repository. So, now that we have the FoodsController, and we’re expecting it to be passed in, if we go ahead and look at our API call for Foods again, we’re going to run into an error pretty quickly, and this error is that the controller itself doesn’t have a parameterless public constructor. The default in Web API is that all of these controllers have to have no input parameters at all. We’re going to change this by allowing a dependency injection container. We’re going to show you using Ninject, but you can use any of the others out there, StructureMap, Unity, whatever in version of control or IOC container you want to use, is valid here. I’m just going to show you Ninject because it is one that I’m comfortable and does the job pretty easily. So, the job of Ninject is going to be to pass in these dependencies into the controller as necessary. We do this by simply going back to NuGet, and we’re going to look for a package called Ninject MVC 3. Now, that’s a little confusing because this was actually written for MVC 3, but it continues to work for MVC 4, and I have the secret wish that they would just call this Ninject.ASP.NET MVC3, but, be that as it may, it’s a pretty solid package that hasn’t needed to have many changes, so I’m just going to go ahead and add it in. And, this is going to add a new class into our App Start called NinjectWebCommon. This is a startup bootstrap, if you want to think about it that way. This is simply something that when the web server comes up and gets started, it’s going to do its own registration. At the bottom of this new class there’s going to be a special method called RegisterServices. And this where you’re actually going to add code to register the type of services you want the dependency injection layer to be able to pass through to any object that needs it, most notably controllers. We can do this by using this kernel object that is being passed in, and we can say Bind, and then pass it in in the interface we’re interested in. In this case, it’s going to be the CountingKsRepository, and we’re going to Bind it to CountingKsRepository. So, we’re essentially telling the container here, when someone requests this, give them an instance of this, and if you have to, go ahead and create a new instance of the CountingKsRepository, and pass it through to them. Now, we have a problem here, because we’ve registered this CountingKsRepository, but you and I have already seen that it requires a context object to be passed in. And, so in that same way, we also want to Bind that someone asks for this context object, to Bind it to an instance of that object as well. Notice, we’re not using an interface because the context itself doesn’t have an abstraction to the interface. Not all implementations of the repository will require a context, so maybe this won’t be necessary, but one of the magic things about dependency injection is that when we ask for something like the ICountingKsRepository, like we’ve done in the constructor, it’s going to look through this list and go, oh, they want this, therefore I need to give them a new instance of this class. I can do that. But, wait, there isn’t an empty constructor here. Let me look at the constructor, and what its input parameters are. They need a CountingKs contex. Let me see if I know about that as well. Oh, I do. I’ll just go ahead and create it to pass into the instance of CountingKsRepository so that I can then fulfill the request to passing in the repository to the controller itself. So, it’s going to handle those interdependencies, even as they change without us having to have the controller accept a context object and a repository, and maybe later there might be a logging component, or there might be a mail component, or any other sorts of different components that the repository needs. At this point, we only know that we need this, and we’re going to let the Ninject system handle the rest of the dependency management for the other objects that are related there. And, right now, if we were doing simple ASP.NET MVC, this would just work. The Ninject itself knows about it. But, if we go back to the browser, and Refresh, we’re going to actually get the same error. That’s weird. Why are we getting the same error? The reason is that Ninject doesn’t know about Web API out of the box. So, if we look at the Ninject here, we’ll actually see that it’s going to know about HttpApplications, and so, because of that it’s being grandfathered in to being able to be used in MVC controllers, but not Web API controllers. So we have to make one other small change here. We need to Support WebApi. This requires one additional package. Let’s go back to NuGet, and this time we’re going to look for WebApiContrib.IoC.Ninject. This is a special project out of an open source project called WebApiContrib, which is a set of tools that can be used with Web API. There’s a bunch of little utilities that are in WebApiContrib that can help you build Web API components. And in this case, it has support for Ninject in the IOC container. So, let’s go ahead and add it. It’s a nice quick Install. And then here we’re going to go to the GlobalConfiguration, which is part of Web API, and look for the DependencyResolver inside Web API. This is the thing that knows how to handle dependency injection in Web API itself. And, we’re going to use as the DependencyResolver a new instance of this class called the NinjectResolver. Let me add that namespace, and we’re going to pass it in our kernel object, the object that we can use to do these resolutions to dependencies. By adding this magic line into our project to Support WebApi, our APIs will now work again. So that we’re going to enable it ourselves to use the dependency injection to handle the requirements for certain kinds of objects we’ll need, and we’re going to need more than just the repository. Later on we’re going to introduce some different ones, like security, libraries, and things like that, that we’re going to need in Web API, and this will set us up with that standard framework that we need to handle the dependency resolution. Now, let’s talk about the real objects we’re going to return from our APIs. Models vs. Entities

So, now let’s introduce you to the concept of Models versus Entities. You’ll notice that in our code here for our FoodsController that we’re actually returning the actual entities that are being returned by the repository. We’re exposing the actual entity objects we’re getting from the database, the raw objects. And, in some cases, that might be fine, but it tends to overcomplicate it to return the entities. Often you’re going to want to control what is being sent back to the users a little more. You see here, when we call the API, that we’re returning just the foods themselves, right? We’re getting these empty collection of measures. We’d like to actually be returning the measures as well. So, let’s do that. There’s a call in the repository that is GetAllFoodsWithMeasures. This goes ahead and includes the measures in the result. So, we don’t have to really change our result, but in this case, we’re now going to attempt to return an object graph. But when we look at our result, the serialization is going to fail. Now, the reason it’s going to fail is that it has found what’s called the self-referencing loop in a property of our food entity. The reason is is that often when you’re building your actual data storage, let’s go over to the Food, we can see that Food has a collection of Measures, and that’s fine. But, what about Measure itself? Measure has an instance of the Food that’s related to it, so that we can easily navigate from Measure up to Food, and from Food down to its Measures. But this is a circular reference as far as serialization goes. It looks at the Food, goes, okay, I know what the properties on it are. Then looks at the Measures inside the Food and starts to serialize them, but when it gets to Food, it goes, it looks like I need a Food related to Measure, so I’m going to serialize the Food, which then creates more Measures, or Food, or Measure, or Food, or Measure, and it could go on forever, and so it detects these circular references, and it doesn’t know what to do with them. There’s a lot of ways you can solve this, and let’s talk about a couple of them. Let’s try solving this by just returning the data we want. Let’s take advantage of Link to use Select. So, I’m going to use Select, and I’m just going to create a new anonymous type to return. (Typing) And I will say Description equals, so I need a lambda here for Food. Notice that I’m cutting off the ID here because it may or may not be useful to include it. So, we can decide about shaping the data here using this facility. But of course, the results doesn’t like this because we told it we were returning an IEnumerable collection of Food, but we’re retuning anonymous types as well, so we can just say object, because we are, in fact, returning a series of objects. And if we do this, we’re going to run into the same problem. Because our Measures still reference a Food object, which then references Measures and Foods, and etc., so we need to actually do Measures.Select, and follow that same pattern. And I’ll just include a couple of properties here. I’ll say Description and Calories equals m.Calories. I could go and include them all, but this will tell it to go ahead and create a new collection from the Measures that only include the data we want as well. So, in this way we’re getting all that descriptive information, we’re getting around the serial recursion because we’re deciding what actually belongs in the serialized objects. So, for every 3 Oz of Abalone that someone eats, that’s 82 calories, and in the case of this juice I can’t pronounce, 1 Cup is 55, 1 Fl Oz is 6.9. You can see we’re actually starting to get some information that someone using our API could actually benefit from. But this becomes pretty fragile, because you’re going to want to return these new sorts of objects in a number of different places, and Copy and Pasting this in every place is going to be problematic. So maybe instead, you want to return something more concrete. So, let’s go ahead and do that. Let’s create a new model. There is a Models folder here. Let’s go ahead and create a new Model Class for Food. And I typically take the name of the entity and postpend it with Model. Some people like to use different words for it; I like to use Model because it becomes pretty simple. And here I’ll do the same thing I did before. I’ll just use Description, and notice I’m saying for the Measures I’m going to assume there will be a MeasureModel, and, in fact, I’m going to use the refactoring to give me that MeasureModel. Let’s generate a new type, call it MeasureModel, put in a MeasureModel Class, and here we’ll do the same thing, prop, and we can include more options here, but for now that should be good. And then that means over here in the controller, all we need to do is instead of returning an anonymous type, we can just say FoodModel, and because we use the same name, that’ll just work. Let’s bring in the namespace for models, and then the same here, new MeasureModel. And this comes back to where we can actually tell it the type of enumeration, in this case FoodModel. We’re essentially getting the same results back, but we’re using concrete classes on the server, so we can be a little bit sure that breaking changes are going to actually break something. Again, the problem with this approach is that we’re telling it that we have some fixed creation of these models that we’re going to end up having to copy everywhere. So, instead of doing this, I like to use a pattern called a ModelFactory. I’m going to create a new class and just call it ModelFactory. There are a number of ways to kind of handle this. Many of you out there are probably already nodding back and forth thinking, well, couldn’t we use something like AutoMapper for this, and, in fact, AutoMapper is really interesting until you need to get information about the URIs, or that include the request itself. And this is a pretty common case in Web API. We’ll see this later when we talk about how we’re going to use certain parts of the API. So instead of that, I’m using a method here where I can actually write a little code to determine how to build each of these different model types. So, in the ModelFactory, I’m going to have a public method that’s going to return a FoodModel, and I’m just going to call Create, and it’s going to take a Food. So, the use case here is we’re going to pass in an individual food and it’s going to Create an individual FoodModel itself. So, in fact, we’re going to do basically what we’ve done here. (Typing) As we’re just creating a common place that we can do this. Return a new FoodModel. Let’s bring it here so it’s a little bit more pretty. And, then instead of creating the new model here, we’re just going to say Select, Create, m. So when we do the Select for Measures, we’re going to call the Create on this FoodModel. Make this public because we’re going to need it in other places. And, we’re going to do the same thing. In here, we’re going to say return a new instance of the MeasureModel that copies in all the data that we really care about. The reason why this works well is it creates one place where all of this mapping between the Measure and the Food is happening. In fact, we’ll do the same operation, but in reverse, when we need to take a FoodModel and generate a Food object, or really, what I like to think of it as, parsing into a Food object for us, and we’ll see that later on in the course. This works well because now our Select becomes as simple as saying modelFactory.Create and create the model for us. Let’s go ahead and create an instance of this and say modelFactory = new ModelFactory. We’ll get into later why we’re creating this in the controller instead of creating it using dependency injection. Now, what you’ll notice here in this pattern is that I’m telling the ModelFactory to just create a FoodModel for me, and then, inside of this, it will know how to generate the subobject. In this case, it will know how to create the Measures as well. And this ends up being fairly helpful in our construction of these objects, because later we’re going to want to make some custom changes to the way that these models are generated in a variety of ways. For example, if we go back to the code in the ModelFactory, we may decide that the calories may be a double value, but we want to always control the way it looks. So we may decide to just say Math.Round to make sure that the calories that we’re applying to the user are actually rounded values. See, we’ve lost all the decimal places, and it’s rounding to the nearest value now. Because we’re creating these, we can then use this in the same way to handle other parts of our controller. So, if we say public FoodModel Get id, if we expose getting an individual food object, we can then just very simply say repo.GetFood, which is going to take our id, and this returns the actual food, so we can go ahead and say ModelFactory.Create, and just wrap it to return our individual object, so that we’re defining what creation of a FoodModel looks like, but then we can use it in any of the cases where we end up having to return one of these FoodModels. So, we look at Foods and go ahead and just say Food with the ID of 1. You can see we’re now able to return that same format; description, measures, each of the measures computed in the same way without having to worry about where we’re handling all that mapping code. Let’s talk about routing next. Routing and Parameters

So Web API has some specific features around how routing and parameter handling are done. And that’s what we’re going to talk about next. If we look at the configuration for Web API, you notice that we have this DefaultApi route that it throws in there for us, and it’s going to take this pattern of API, controller, and then id. This is only one route. You might have a number of these, and, in fact, in the way we’re going to build our API, we’re going to have one of these for each of the individual types of data we’re dealing with. So, I’m going to create a new one of these and I’m going to call it our Food route. And instead of it being just API controller, I’m going to say that we’re going to segment our nutrition information inside a tag that says API nutrition and actually just say foods. In this case, because I don’t have a parameter for controller, I’m going to have to tell it that the controller is going to be Foods, and that the id is still going to be an optional parameter. It’s going to allow us to say, for this specific route, we want to define what the template for the route is going to be. That means that we can now change our URI to nutrition/foods, and it’s going to then call our controller itself. So, this routing is determining how we’re going to get to each individual item here. This DefaultApi is useful if you’re creating a very simple API. It’s very useful for the demo case, but, in fact, I like to get rid of it entirely and map my APIs separately, and we’ll see as we build in the next module some more mature routes why we’re going to want to have each of these defined separately. This also means if we end up exposing an API, maybe we’re in the middle of testing, adding a new controller to our code, that we’re not going to accidentally expose it out to our API by default, because we aren’t going to have one of these default routes that are just going to map specific controllers to some fallback mechanism. Some people can find that useful; I don’t. I’d rather be a little bit more stringent in the way I’m defining these routes. One of the things we can do here is, in addition to the route, we can also have constraints. And what constraints are going to do is, again, allow us to create an anonymous object here to say that for the different parameters, and in this case we only have one, we’re going to want to be able to constrain what this parameter looks like. Now, by default, the object is already going to be constrained id to an integer, because our API includes an integer. For an integer, this isn’t all that necessary. We could create a constraint here that said /d+. And what this really tells it is this is a regular expression we’re going to use to constrain what is actually mapped into the ID. But, of course, this is the same as integers. As long as the number isn’t outside the range of an integer, the API is already going to constrain it by throwing an error if that ID isn’t valid. We saw that earlier in this module. What’s more interesting is if the ID had been a string. Let’s say we are storing the numbers as strings, then this constraint becomes important. We will actually see this in the next module when we’re going to map an ID type to an actual date, so we can constrain it to look like a date. But, for our particular case, we’re going to let the data types actually do the constraining for us. The other piece here is parameter mapping. So, by convention, because our route has an id here, it’s going to take whatever the value is here, and try to match it to an instance of Get if a Get is being pursued, or Post if it’s a Post, or Put if it’s a Put, whatever the verb is, to the name of the parameters here. Because we specified it as being an id in the name of the routeTemplate, in the routeTemplate itself the name of this parameter has to be id. If we change this to foodid, we have to change it in all three places. (Typing) And in our case, actually four. So, we go back over to the browser, and we say 1, it’s still going to work because in all cases it’s trying to map it to the name, in this case that is foodid. But what if we had additional parameters like foodsIncludesMeasures=false. Now, because it’s part of the query string, it’s pretty much going to ignore it. We could certainly parse the query string from the request and do some interesting things about it, but Web API actually has mapping built-in for that. So, if in the Get I include, let’s say a Boolean for includeMeasures, this will expect that there is a Measures parameter always included. But, I’m going to go ahead and assign it to true to be the default behavior. So, in this case, we’re going to be passing in that includeMeasures sometimes. So, let’s refactor our example here just a little. And let’s call this our query. And let’s actually define it up here as IQueryable Food and if includeMeasures is true, then we’ll include the Measures in the query, else, we’ll say query equals repo.GetAllFoods, which isn’t going to include the embedded Measures. Now we can still have our result as query dot all these other pieces. And so, in this case we can use parameters to specify the behavior of this method. I’m going to go ahead and put our “s” back in there. Because this is assigned true by default, that means in our case, just getting foods without the parameter is still going to work, because it’s going to assume the value is yes, I want the measures included, but in cases where the user may just want a dropdown list, we can say includeMeasures equals false, we’re going to see the measures will be stripped out. It’s going to allow us to simply map other types of parameters directly into the parameters of our calls. Here it’s going to assume that if we includeMeasures, it has to be something that is convertible to a Boolean. I guess, sort of, a self-constraint in that way. This will become more important later when we use some of the other verbs, because it’s going to be able to take shapes that are being passed to us. Let’s say if we’re doing a Post for a new food, as long as the shape of that food looks like a FoodModel, it will go ahead and map it directly into those types as well, has this inference of the shape of data that’s coming in to the data types that are in .NET, true and false for Booleans, numbers for numbers, and even structures into structures. So, if we pass in something that looks like a food with measures in it, it’s going to take that entire object graph and will be able to infer how to actually get it back into the actual objects. Let’s wrap up this module. Summary

So far in this module we’ve built a couple of quick calls, we’ve built our first API controller, as well as gotten some data to be returned back to the browser. But, we’re not nearly done. We’ve sort of introduced you to a lot of the high-level concept of Web API. In the next module we’re going to actually delve down into how to build that API complete with all the different verbs that we’re going to need for different types, including things like associations, and shaping the data in some different ways. What we’ve learned in this module is that REST is important, but we want to be pragmatic. We want to worry about being RESTful enough to get our work done, versus trying to stick to the dogma that tends to be what REST is talked about. We’ve seen the Web API is a good choice for building these APIs because it’s separating the ideas. It’s separating constructing objects, from the serialization, from the formats, so that the APIs can do most of the work that needs to be done without you having to handhold or touch it in every individual call. I’ve shown you how to add Web API to an existing project that’s using .NET 4 or above. And we’ve seen that Web API leans on these HTTP verbs so that the names of the operations inside of an API controller are mapped to the same HTTP verbs that are the basis of what REST operations are. I’ve shown you that I like to separate your Entities from the actual payloads that you’re being delivered from the API, and that as we build it out across the modules of this course, hopefully you’ll see the additional benefits of going through the extra step of separating Entities from the APIs themselves. And I’ve shown you how Routing and Mapping of Parameters is using conventions. It’s trying to be smart about guessing what the right thing to do is. Sometimes you’ll have to make modifications to make sure that those conventions are met. But, for the most part, as long as you’re routing table is correctly configured, it’s going to be able to find out how to get at the different operations in an API controller, as well as how to map data being passed to you to parameters inside of those API controller methods. This has been Module 1. My name is Shawn Wildermuth of Wilder Minds. Thank you. API Basics Introduction

Welcome to Module 2 of Implementing an API in ASP.NET Web API. In this module, we’re going to talking about API Basics. My name is Shawn Wildermuth with Wilder Minds. In this module, we’re going to start by talking about what we’re actually building. Then we’ll dive into Identifiers, implementing an Association, preparing for Security, implementing a POST operation, implementing a DELETE operation, implementing PUT and PATCH operations, implementing Paging, and finally implementing RPC-Style Calls. Let’s get started. What are We Building?

In the first module of this course, we started by showing you how Web API works, and in doing this we started to build our API for accessing a food database that’s full of nutrition information. Let’s talk about what the API is actually going to look like, and we’re going to implement most of this in this module. As we saw in module one, we’re going to support a Get to an API under nutrition called foods that will get a list of foods. So this is going to include a couple parameters like Page for paging, and includeMeasures to include the different measures for each of those foods. In addition, the API will allow users to get information on a specific food by ID. In the same way we’re going to support getting the associated measures for a specific food using the same path syntax. In addition, be able to refer to a single measure as it’s related to a single food. The API will also empower the building of diaries based on specific users. These user diaries are going to be a collection of foods that were eaten, along with quantities of those foods for a particular day, so that they can compute the nutritional information for the food that they have consumed for a particular day. To empower this, we’re going to support getting a list of diaries for the current user logged in. We’re going to allow them to Post a new diary for a specific date. We’re going to allow them to Get a specific diary, including the related diary entries. We’re going to allow them to Delete an individual diary, and Get a summary for a particular day that will include all the nutritional content for a single day’s diary. We’re also going to support the idea of diary entries, and these are individual entries for a particular day. So, by looking at a particular diary, the API will support getting the entries for that day, allow you to Post a new entry for that day, will allow you to Get an individual diary entry, will allow you to Update an individual diary entry, as well as Delete an individual diary entry. So, we’ve seen the different parts of the API that we want to support building, and that’s what we’re going to do in this module. So, let’s hit Web API to start implementing our API design. Implementing an Association

So, let’s start by implementing the association of measures under foods. So, here we have our Visual Studio project right where we left it at the end of module one. So, if we simply just run this project, we can look at the api/nutrition/foods as the API we developed earlier. Remember, we developed the ability to return not only the information about the individual objects, but the information about the specific measures, which currently only includes calories. We also allowed it to return an individual food by ID by implementing a Get with the ID embedded in it. All of this we already accomplished in module one. What we want to do next is support the idea of retrieving the measures for a particular food. And by going to measures, it’s going to show us a 404 because we haven’t implemented it yet. We need to take this pattern that we’re building up here, and implement it on the server. To start this process, we’re going to go to the WebApiConfig file under App_Start, and if you remember from module one, this is where we had configured our Route for Foods. We’re going to actually create a new route for our association. Even though to the user of the API this is going to look like an association, this is going to be its own route. It’s just going to be nested underneath the food route. So, I’m going to make a Copy of that new route, and we have to give it a unique name, and so in this case we’re going to call it our Measures Route, and we’re going to want to take this routeTemplate and expand it to include measures, as well as the id for measures. So, even though the beginning here is the same, as we add new elements at the end of the routeTemplate it’s no longer going to match, and so it’s going to come down here and match this one instead. In this case, we’re going to create a new controller that we’re going to call the MeasuresController, so I’ll go ahead and put the word “measures” in there so it can find a class called MeasuresController that we’ll create in a minute. And, in this case, the foodid is no longer optional. In order for us to return the measures, or a specific measure for a food, the foodid must be supplied. So, we can eliminate this as Optional for foodid, but we want to make sure that the id itself is Optional. So, in this way, the same Route can support looking for measures under a food, or the specific measure underneath a food; either the collection of measures for a particular food, or the individual measure underneath that particular food. So, we have that configured. Next, we want a controller. So, I’m going to say Add Controller to the Controller’s folder, just like we did in module one. I’m going to call it Measures, and I’m calling it Measures because that’s what I specified here in the Route. These are going to be matched because of that name. And, just like we did with the FoodsController earlier, we’re going to create a new constructor, and that constructor is going to take an instance of the repository, and let’s just bring in that namespace, and I’ll just use refactoring here to generate a field for the repository so we can use it. We’re also going to want to create an instance of the modelFactory. This code should look familiar if you remember what we did in module one, and bring in that namespace, and again I’m going to use throw a period and just use the refactoring to create the private field for me. So, we now have the elements we need to build the Get method. So, let’s go ahead and create public IEnumerable and, again, we'll bring in that namespace. And, so in constructing this, it's going to look a lot like what we saw in the FoodsController. If we go over to the FoodsController, we simply had a Get that has some optional parameters, but that return IEnumerable lists that we're going to eventually get from the repository. But this is a little different. We actually have a required field here, and that is the foodid. Now why is the foodid required inside the MeasuresController? It's required because, if you remember, in the configuration of the Route, we told it that we wanted the measures, and that the id was Optional as one of the RouteParameters, but that the foodid parameter, because we didn't list it inside the defaults, is not optional. So, any parameters you put in here with the little curly braces won't be optional unless you specifically mention it. And in this case, the foodid is required so we know which measures you're going after. And then it's a matter of just writing the code for retrieving the data in those measures. And, here we have a method on the repository called GetMeasuresForFood where we can just give it our foodid. And just like before, we're going to want to use Select and the modelFactory to Create our models of measure. So, that means this is going to return a MeasureModel. Now, we already built the MeasureModel, and, in fact, we already built the Create for the modelFactory because we were using it inside of the FoodsController. The FoodsController is building up both Foods and related Measures. We're just going to leverage that same facility to go ahead and Get the Measures for a specific foodid. If you're using the Entity Framework, this Select is going to attempt to perform this task on the database server itself. And, so, typically you're going to, before you do your Select, call ToList to force the underlying data store to retrieve the data into a list, and then we'll go ahead and transform it into the collection of our model objects. So, we're now getting the measures for this particular food. Of course, if we look back at our call to this food, we can tell that this is really just this part of the call, when we asked for the measures for this particular call. In that same way, we can implement the rest of the association by creating a another method that's going to return a single MeasureModel, and again, we still need to know what food we're going after, but in this case we're also going to ask for the id of which measure they're looking for. In order to get this, we'll just do the same thing we did before, but in this case, we'll ask our repository to just get the individual measure. Now, in this case, we're not really using the foodid, but it might be a good idea to go ahead and check the foodid, if the results.Food.Food.Id equals the foodid. So, we're just going to guarantee that this measure in fact belongs underneath this foodid. So there's a consistency, we'll go ahead and just return_modelFactory.Create(results);, otherwise we'll return a null. This means that we can go ahead and Get an individual measure. There's no indication here of what the ID of the individual measures here, so how do we know to make this 1. I happen to know it is 1, but we're going to add in the next module a way for us to look at what the actual URL for each of our elements is. That becomes important to describe to the user what individual items on the server are represented by what URL, so that they're easier to deal with. And, in fact, I prefer this to the approach of just putting IDs here, and then having the users of your API have to figure out where that ID belongs in a particular URI. So, let's do that next. Identifiers

So, let’s talk about identifiers in your APIs. As we saw in the last short video, we’d like to be able to know how to retrieve each of the individual parts of the data structures we’re returning, and one approach here, and the approach that I advocate, is that each of the source of objects that you’re returning here should be able to tell about its URL, the URL that points to this item on your server. And so this is something we’re going to want to add to the model classes that are returned. You might say, well why don’t we just return the IDs and then document it well enough for them to know that nutrition, foods/id is what you need to do here. That’s certainly valid, but I find it more descriptive to use an entire URL. Especially as the nature of the paths might get changed, especially in versioning, you want the URL to be specific where it is on the server. So, let’s do that. We go down to the Models. Let’s start with the FoodModel and go ahead and create a new property called Url. And I’m going to do to the same thing to the MeasureModel because we want that to be available in both cases. So, we really want the magic here to happen when we use the ModelFactory. So, let’s open up that ModelFactory, and figure out how we want to do this. We now have the Create method that knows how to create an individual FoodModel. We could certainly go ahead and just do a string.Format, and then just pass in the food.Id, and this certainly will work. Let’s give this just an empty string for now. We’ll come back and do this. Now if we build this, we can actually see the URL show up here as part of the description. I like to make sure it’s first, but it’s not super important that it’s first, as long as it’s available. The problem with just using string concatenation here we see right away, and that is localhost, right? Suddenly, the modelFactory is going to have to know about how this is being served, whether it’s being served in IAS as part of testing for the developer, or maybe it’s in the staging, or testing, or production server, it’s going to have some knowledge of how to figure that out. And there is a way we could write the code to do that. The other problem is that if we change our routes, if we come in here later and decide during the process that instead of nutrition that we wanted to call it something else, we’re going to have to go find all the instances, or the code, where that belongs. What would be nice is if we could actually ask Web API to construct the URL based on what it knows about the routes. In fact, that’s exactly what you can do. So, inside the ModelFactory, I’m going to create a new constructor, and I want to create something called an UrlHelper. Now, when you use the UrlHelper, there’s going to be one for ASP.NET MVC and one for Web API. Make sure you get the one from Web API, which is in System.Web.Http.Routing. It can get very confusing, especially the kinds of error message you’re going to get if you’re trying to use the wrong UrlHelper. Now the UrlHelper, even though it has an empty constructor, actually requires the request that is being used for the individual call. It’s using this request to discern some information about how to get back to the routes. The problem is the ModelFactory doesn’t have access to that, and this requirement of having the request is one of the reasons why using something like AutoMapper falls apart, because we have to have a way during the construction of our controller to feed this into our ModelFactory so that we can use it here in our helper. And the trick here is to actually pass in an HttpRequestMessage, which is the object it’s expecting. Let’s bring in that namespace, and refactor this to add the field. Once we have the UrlHelper, it becomes much easier, because what we can do is say urlHelper.Link. This is much like action links in ASP.NET MVC. We’re going to give it, in this case, a Route name, which is Food, and then an anonymous object that contains any of the Route elements, and in this case this is just going to be foodid = food.Id. So, we’re constructing an object that has all of the parts of the API that are required, and letting the UrlHelper determine what the URI actually looks like. We need to capitalize that since it’s capitalized in the food object, and I’ll go ahead and do the same down here, where we can say Measures, which is what we called that Route, and here the foodid will actually be measure.Food.Id, id = measure.Id. So, now we have the ModelFactory actually creating those URL links for us. Great! We do have the problem though we need to be able to pass in this request now. If we go ahead and Build, it’s going to complain that we need to be able to construct the ModelFactory in both of our controllers. We can’t do it here because even if we do say this.Request, this request at the time of the construction of the controller is empty, because we’re right here in the constructor, of course. So, what we really need to do is defer the creation of this ModelFactory. And so a pattern for simplifying some of this code, because we’re going to be using the ModelFactory, and probably the repository in a great many of our controllers, is let’s go ahead and create a BaseController that we can move some of this common code to. So, I’m going to create a new controller class, but this time I’m going to call it BaseController, and all of our other controllers are going to be, not surprisingly, based on this class. I’m going to mark it as abstract so no one actually instantiates an instance of BaseController. We’re only going to be inheriting from it, so we can have some of the shared functionality. So, let’s do a little editor inheritance here, and I’m going to Copy the properties from the FoodsController, and the actual constructor, over to my BaseController, and I’ll need to fix up some namespace inclusions, and, of course, this is going to be BaseController. We’re also not going to want to create the ModelFactory here in the constructor because it’s too early. We actually want to defer it until we’re actually going to use the ModelFactory. And so a trick there is to just create a Deferred property. So, I’m going to say protected ModelFactory TheModelFactory. You can call it whatever you want, this is just a pattern of naming things that I’ve gotten used to. Now, we’re just going to say if the modelFactory is null, in other words, we have not created an instance yet. Go ahead and create modelFactory = new_ModelFactory(this.Request);. Most likely the first person in that needs the ModelFactory is going to be inside of one of these methods, and so this should be late enough for the request not to be null in this case. And we’ll go ahead and return the modelFactory. The second person that needs the modelFactory, this won’t be null anymore, it’ll just go ahead and return the same instance over, and over, and over again. We should go ahead and also expose as a protected member, TheRepository. In this case, we don’t need to worry about deferring creation, we can just say return the repository. Now, we could have made these protected, and just given access to them, but I’ve gotten used to always using properties when communicating in between, so that way I can intercept. If later, I need to defer the creation of the repository, I don’t then have to refactor a bunch of code to do this. I already have this Get being called. I can just expand the amount of code that’s in this Get call. So, let’s go fix up the two controllers. In these cases, we don’t need the members anymore, but we still need to expect that the repository is going passed to us. But, instead of us doing anything with them, we’re just going to call the base class with the repository to do the right thing. We will need to change our BaseController name, and I misnamed it. I like to call it BaseApiController so we know that it’s the BaseController for the ApiControllers, not for any other controllers in our project. And, in fact, to be clear and concise, I’ll go ahead and change the file name as well. So, again, our FoodsController now derives from BaseApiController, which then derives from ApiController, so we’re just creating a class shim in between the two, and when we ask for the repository, we’re just passing it down to the base class, because that’s really where that’s going to be stored. It does mean that all our instances of repo will now need to be TheRepository. Let’s hope I spelled that right. And, same with modelFactory. And, I’ll quickly do the same thing for measures, though I won’t make you watch me. Glad you’re back. Now, we have both the MeasuresController refactored, as well as the FoodsController. And this means that because we’re creating our ModelFactory with a valid request, these URLs should go ahead and produce links for each of our objects for us. And with luck, we’re now creating these based on the Web API routes themselves. So, then instead of having to know that this ID is actually 1 or 2, we just know that this is the URL that we’ll retrieve, or later on when we do read and write entities, ones that we could Post to, or Put to, or Delete to, or Patch to. In fact, if we just click over, we can see that this is going to take us directly to that individual measure, or to that individual food. And even the whole collection of foods now is going to include that URL for each of those different entities that are going to be included in the results that our users are then going to use. At this point, we have the API done for Foods and Measures, because all we’re doing is allowing Read Only access into the Food and Measure database essentially. Now, we want to move over to the user specific API, and let’s go ahead and implement that next. Preparing for Security

So, next, let’s talk about security APIs. We need to prepare for security, and then in module three, we’ll talk about how to actually implement security. But, at this point, we just want to prepare our APIs for security. Now, why do we want to do this? So far we’ve been looking at APIs that expose data out, and we may want to limit what applications can get at this API, and we’ll talk about that in module three, but for our new data we want to collect, we want to collect it on a per user basis. This means, we need to know about the current user that is using the API. And again, we’re going to talk about how to secure it next, but this means that for our next set of APIs, we’re going to need to have the context of who the current user is. Let’s start by going ahead and just creating a new Route for our diaries. (Typing) And I’m going to call this the Diaries Route. In this case, I’m going to put it in a path of user, and then diaries. Now, I’m putting it down one level because we might have some other user data later, but for now, diaries is all we care about. And in this case, we’re going to call the parameter diaryid. And, if you remember back to the description of this API, this diaryid was just going to be a date string; Year, Month, Day. So, let’s change the controller to a diaries controller, and let’s make sure that it knows that diaryid is going to be Optional. It can be Optional because if we look at api/user/diaries, it should return the diaries for the current user. Now, if we include the diaryid, it’ll return just that date diary, if any. We’re going to come back to a couple of pieces to this in a minute, but let’s go ahead and create our controller. I’m going to call it the DiariesController, and because we’re using the new base class, I’ll go ahead and change our base class to the BaseApiController, and let’s go ahead and create our constructor, and go ahead and call our base class with the repository, so that we’re wiring all that together. So, that’s great. Now we’re going to want to implement getting of all of a specific user’s diaries. So, I’m going to start with this just as object, so we can talk about some things, and then we’ll get back to converting them to models. Now, we’re going to start with an empty Get because the only parameter in our Route is the diaryid, and we’ve said it’s Optional, so let’s go ahead and implement returning the collection of diaries first. So, we can go ahead and get results by calling TheRepository. Remember, that’s part of the base class now. And, we could ask for GetDiaries, and GetDiaries is going to ask for the username. And this is where it starts to get into the problem of I’m calling this API, but the data that’s being returned is going to depend on what the user is. Now, we could ask for the user to be supplied to me, but I’m going to want to get into the security pipeline, and so I want to just have a way to Get the current user while I’m in this method. I do not want to be passing in the username here, because it doesn’t guarantee that I’ve authenticated against that user. So, what we’d like to do is be able to get the username from somewhere, and one of the common places you’ll see people do this is, is Thread.CurrentPrincipal.Identity.Name. And, if they’re authenticated, that will return a magic string. This works fine, except that it’s not going to make our controllers very testable, because in order to test the controller, we’re going to have then inject a custom principal into the thread for our tests. So this doesn’t work really well for me. What I’d like to do is be able to pass in another object that I’ll call ICountingKsIdentityService, and I will create a local variable for that in a minute. Now I could push this down into the base class, but not all of our controllers are going to require the identity service. Our Food and Measure controllers don’t need to know about the identity, so I can just go ahead and keep it here at our controller level. I might create two types of BaseApiControllers, one with Identity and one without if I was doing this more rigorously, but to show you what we’re doing, I think this is good enough. Let’s go build this, and wire it up to Ninject so we can bring it into our project. I’m going to create a new folder called Services, and to this I’m going to Add a new Class I’m going to call CountingKsIdentityService. So this is simple implementation of an interface that we’re going to extract in a minute. And, this is just going to have a public property called CurrentUser. When someone calls it, I’m just going to return a hardcoded string for now. Later, in the next module, we’re going to come back and implement this. But, for now, that’s going to be good enough that we’re just going to return some hardcoded string, so we can start doing some tests. This username is actually embedded in the Entity Framework project so that it seeds a couple of diary entries for this user, so, I’m using this username very specifically so I can get started with getting data and showing data in the browser. Now that we have that, let’s go ahead and use refactoring to Extract the Interface. That all looks good. We got our interface. It’s going to need to be public, and finally, let’s go add it to the Ninject, so under App_Start, NinjectWebCommon. If you remember from the first module, we used this to register the services that it’s going to inject into different controllers, so I’ll just Bind our ICountingKsIdentityService To CountingKsIdentityService. So at this point we have an actual object that’s going to return to us some identity name, which is good enough. And, we’ve injected it so it will, in fact, be injected into our controller for us. Now, we just need to have it inside of our controller, so I’ll go ahead and create a field for it. So, I’m going to get that current username out, and then use it to pass in the GetDiaries to actually get our data back. And, because the repository allows me to query, I’m going to go ahead and tell it to OrderByDescending date of the diary. I’m going to tell it to only return the last 10, because we may implement paging later. And then go ahead and Execute that query. I’m also going to want to then Select, just like we’ve been doing before, and go ahead and Create our model classes. Let’s come up here and change the return type now to IEnumerable. And right now we don't have the model built, so let's go ahead and do that real quick. Let's go to the Model folder, Add a new Class. I'll call it the DiaryModel. This process is identical to what we did in module one, where we created a model class and then eventually extended the ModelFactory to include a way to create these. So, I'm going to create an URL, just like we have for Food and Measures. We want an URL to point at this specific diary. We also need a DateTime for CurrentDate, and then eventually we're going to need a property for DiaryEntryModel. This will be the list of Entries for a particular diary. But, we're not going to go that far quite yet. What we want to be able to do is get the URL back and get the date back. So inside of our DiariesController, we can now bring this model class into our project, but notice the Create is still complaining because we don't have a create overload for Diary and DiaryModel yet. So, let's just press period and tell it to create the method stub and F12 to go ahead and navigate over. Now it was trying to guess what the return type was, and guessed it was a FoodModel, which, of course, is wrong. This is going to be a DiaryModel, and then we can just re-create it like we did before, DiaryModel, URL = urlHelper.Link. So, notice that we're creating the link to the diaries based on the diaryid and then the CurrentDate. We're not using the ID in this case. We're going to actually specify per CurrentDate, which means we're going to have protect it from creating duplicate diaries for a specific date. We can assume that our database is already set up that way. So, we now can go ahead and create our diary models from our diary. So, we go ahead and run this, and change this to user/diaries. So, it can't find the resource. Let's find out why. This is a really common problem you're going to have, and that is the Route here is failing because it finds this dairyid instead of diary. Again, we've misspelled it here, and it thinks it's required, because the only ID it says is Optional is diaryid. So these have to have exactly the same name. So, if I'm lucky, and I fixed that, we're now getting our diary. But all is not well. We can see that the currentDate doesn't really have a time element, but we're returning it as a standard date, which is fine. But, when we constructed our date as part of the URI using the UrlHelper, it tried to guess what we wanted, and it guessed wrong, because making the date 08/17/2013, and then some strings to represent the 0 time and date, isn't useful at all in what we need. What we really want to do is be able to control what that looks like, but I haven't found a good reusable way to do this. So, as a workaround, since we're always going to be creating this in the factory, the trick is to actually pass in a string. In this case, I'm going to say, ToString, and then specify exactly what I want, which is a four letter year, passed by a two letter month, and a two letter day. So there's a much better looking URI. You may think, well, we could use a constraint here, like we talked about in the first module, to constrain this to look like what we talked, and we can, but the UrlHelper doesn't know how to use the constraint in order to construct what it should look like. So, we don't have a way to really describe what it is. Another option, I'm not a big fan of it in this particular case, is you can say year, day, and then bring them in as individual items, and then you're Get would have to have those multiple items in them. I'm going to leave it as our diaryid, and just deal with it as a string. Because, what's interesting here, if we go back to our DiariesController, and go ahead and implement the individual one, (Typing) notice that the name of the parameter is diaryId, but I'm telling it it's a DateTime, so it's going to attempt to convert it into this DateTime, so that's why that format ends up being important. Let's Copy this little piece for now, and I'll go to the repository and GetDiary. And in this case, the diary requires the username, and the date, so I'll just use the diaryId. And, here's where we start to get into some of the complexities. What if the result is null? And if the result isn't null, then it's easy. We can just say TheModelFactory.Create(result); and be done with it, right? But if it's null, we don't want to just return null, and certainly passing a null here is going to cause a problem. This is where we don't actually want to return the entity type. We want to return a special type of object called an HttpResponseMessage. This HttpResponseMessage allows you to wrap what the result type is, and then have a little bit more control over what the status code is. So, if we say return Request.CreateResponse, this will return an HttpResponseMessage for us, and then we can just say StatusCode equals NotFound. But that also means we have to change it here to say, CreateResponse HttpStatusCode.OK, and pass in the result as second parameter. So, this gets serialized into the body of the message, and this gets put into the header as the StatusCode that was returned. And, this is the right thing to do when developing an API. You want to return good useful status codes. Returning null or empty results, and having them infer what that means isn't useful. You really want to be leveraging these HttpStatusCodes wherever possible, and you're going to see as we implement the rest of the API, we're going to use it quite a lot. So, if we go to this individual diary, we can see it's now returning just that diary based on that string that represents what is the ID for that individual diary. But, if we go ahead and change the date to a date that isn't there, let's look at the debugger real quick, or the Console window and Refresh, you'll see that it's actually returning a 404. So that if we made this request from JavaScript or another API, we could test for what that status code was and know what to do about it. We could alert the user that there is no diary for this date, do you want to create a new one in this case, instead of assuming that null meant there wasn't a diary for the state. We're being very specific about what we want to do in this case. So, now that we have a controller that is set up for dealing with the identity of the current user, let's go ahead and look at actually Saving data, or doing a Post to our API. Implementing POST

So, next let’s implement POST. Now back in Visual Studio, we can see a new type of controller that was created off screen, DiaryEntriesController. Not surprisingly, this is a controller for the diary entries themselves. We created this without showing you the actual code because it was just duplicative with what we’ve done in other instances. You can see the counting repository, the identity service, just like we did with the diary in the last video, and that we just implemented Get using TheRepository for both a collection and an individual object. We’re using the CreateResponse to show when they request a diary entry that doesn’t exist. And then going ahead and returning the correct type of diary entry. We’re also using a DiaryEntryModel, just like we did with the diary in DiaryModel, and we’re using another Create method in TheModelFactory in order to create these new diary entries. If we look and see what this looks like in the browser, We can see that we’re returning a set of diary entries for a particular diary, and we’re creating an URL for each of those diary entries just like we did with the diary. We’re also creating an URL for embedded data. In the case of the entry, it contains the measure and the related food, so all we are returning to the client is the description of the food and measure, as well as an URL directly to that individual measure, as well as the quantity that was consumed. If we follow these links, we can see that we can get back to the exact measure and food that was consumed. Because we implemented the Get that we can see individual entries themselves, as well as a collection of entries within a particular diary. The next step is to allow us to actually add new entries, which is what we’ll do with the Post method. So, let’s go back to our controller, and let’s create a new public, and I’m just going to return an object for now, and we’ll get back and refactor that in a minute, and in order to do a Post, we simply mark it as Post. Like our other methods in this class, we need the diaryId from the path to be included in our Post here, so that we know which diary to add it to. Now, we’re only going to support posting to the collection entries to insert a new object into those entries. We’re not going to allow users to Post directly to an individual ID, because it makes no sense. So, we could go ahead and support inserting this object into our repository, but we need that object. So, here in the parameter list, we’re going to tell it that we want a DiaryEntryModel, and I’ll just call the model, and this is the data that is being passed from the user to us. And, so we want to go ahead and implement what this looks like. Let’s open a Fiddler a second, so we can see what this is going to look like for the actual user. So, in order to Post, let’s go back to our browser, and let’s just borrow this URI, that is the URI to the entries, for this particular diary. And, let’s say we want to add a new entry here. We’re going to Post to that URI. So, this is simply the diaries endpoint, and then the date of that diary, and then the entries. We’re going to Post directly to that. This URI will end up calling the code in this Post method. But we need to be able to pass in what is the data for the diary entry. How do we do that? We actually do that in the Body. So, let’s change this to Post, and let’s go ahead and just format a JSON Body. And when we look back here, we can see that a diary entry is made up of a URL for its own element. We don’t have to actually supply that in Post, because that’s something that’s going to be computed on the backend for them. We have a description and a measure, which are really Read Only elements. These are inferred by the measureUrl. We need a measureUrl to point at what is the actual food being eaten. Not only the food, but all the measures for that food, and then the quantity that they ate. So, let’s start with quantity, and over in Fiddler, just say quantity equals 5. And the only other element we really need here is measureUrl, because we need to be able to identify the kind of food and the measure for that food. So, let’s come over here and let’s go over to our Foods, and as we’re looking through here, let’s decide that they’re going to eat some acorn flour, with lots of fat in it evidently. This is 1 Oz of acorn flour, so I’m just going to Copy the URL for the measure of the acorn flour, and use it here as our measureUrl. So, I’ve got a JSON object here that represents the diary entry. And this JSON object is in the Body of the Request. So, we need to be able to tell it what kind of data we’re sending it. And, so we’re going to need to add headers in here; it’s going to ContentType, and I’ll just applicationJson because I know it’s JSON, and, in fact, Fiddler will add a header for the size. If I try to Execute this right now, it’ll actually come back as a 405, because a Post isn’t allowed yet, we haven’t really compiled that new Post code, so the result of this request is that the requested resource does not support Post. But you notice that when we executed it, it gave us the ContentLength for us. It’s one of the things that Fiddler will do for you is compute that ContentLength so that this request is actually accurate. Now that we know where the data is and what this looks like, let’s go back to the code and understand how we’re going to actually be passed in this Post. The trick is to say FromBody. It’s an attribute that you can put directly on the parameter, and this is going to tell Web API that we want to pass into the Post an object model, so we want it to infer what the JSON is into an instance of the DiaryEntryModel from the Body of that Post. So at this point, we have, or we should be getting an actual valid model. Let’s go ahead and say return null for just a moment, and let’s set a breakpoint here. And back in Fiddler, let’s try to Execute this again, and it should stop us in our code. But at this point we can actually see what we’re getting in the model. The model isn’t null, and if we go ahead and look at the elements, it has mapped into it based on what it could infer from the JSON object. It put the quantity in because we named that correctly, and it brought in the measureUrl. It doesn’t know about the food description, or the measure description, or the URL for this object, because they weren’t supplied, and that’s fine with us. The information of the quantity and measureUrl is enough for us to figure out what this object is. So, let’s stop this and really implement this now that we understand how these parameters are going to be mapped for us. We now, at this point, have an instance of the model, but we have to figure out how to actually inject that into the repository. So, let’s start by throwing out a try/catch, and in the catch let’s just return CreateResponse BadRequest. Now, there’s a couple of different ways we can create this response. The request also allows us to CreateErrorResponse, and this is often helpful, but may leak some information about your backend to users. So use it where you think it makes sense, but in this case, we’re going to create an error response. In the second parameter, when it’s a CreateErrorResponse is one of a couple of things. It can be an Exception, it can be an HTTP ERROR, which you can get sometimes. It could also just be a string, but in our case, let’s go ahead and pass in that Exception. So that if something bad happens, we can actually take this Exception and show it to the user. This way, if there’re problems with the data that’s being passed in, this exception might include the right information. Depending on your security scenario, leaking what is in that Exception information to the end user, may or may not be a good idea. You may decide you just want to send back BadRequest without really giving them an idea of what is wrong. So, now we need to be able to get the actual entity that represents data that’s in the model. And, so we can use TheModelFactory again, and we’re going to create a new type of method in TheModelFactory called Parse. This is going to be the opposite of Create. We’re going to pass in the model and expect that it’s going to return to us a diary entry entity that we can insert into the database. So, I’m going to go ahead and use refactoring just to create the stub, and let’s go over to it. It tried to infer some things, so let’s fix this by saying public and DiaryEntry. And in here, let’s also do a quick try/catch just to say that if we get this far let’s go ahead and return a null. If we couldn’t parse it for one reason or another, we can test on the other side of this that a null happened. Because, sometimes we may want to give them more information about why it failed, and not being able to parse is one of those pieces of information. You could imagine that maybe thinking that there is one too many levels of try/catch here it would be useful, but it’s actually not. So, let’s go ahead and create a new DiaryEntry object, and let’s determine how we can go ahead and parse this information. And the first thing I’m going to do is I’m going to say if the models Quantity does not equal the default of double, double is the data type of Quantity, then that means the Quantity has actually been set. If it has actually been set, then I’ll go ahead and also set it on the entry. Now, we could just set it, even if it was the default, but this way we know it was actually set. The second piece is how do you determine what that URL is pointing to? This is a case where you’re actually going to have to parse the URL, and determine some information about it. In my case, I’m just going to create a new URI, and I’m going to pass it in the model.MeasureUrl. I’m doing this so that I can then get the parts of the URI. I’m doing this so that I can get a string version of the ID of the measure. And, I can look at Segments, and just go ahead and get the Last segment, and then I’m going to say int.Parse. Now, you may wonder why I don’t do TryParse here, and I’m avoiding TryParse here because I want it to fail if the last Segment, if the Measure URI isn’t an integer. We’ll go ahead and return null because we couldn’t figure out what the actual measureId was. And now we need to go ahead and get the objects that represent the Food and Measure based on this new measureId. The problem is that if we call TheRepository, it’s gone. And the reason it’s gone is that it’s not here in the ModelFactory. So, we’re going to want to refactor this to include TheRepository as needed, so I’ll go ahead and add CountingKsRepository, let’s go ahead and bring that in, and then like we’ve done before, I’ll go ahead and just refactor it to Create an instance of it. Then I can just use TheRepository to GetMeasure using that measureId, and then I can set it, entry.Measure = measure; and entry.FoodItem = measure.Food; which is attached to it, and then we can just return that entry. Because, we’ve made this change to the ModelFactory, if we build it quickly, we’ll notice that it doesn’t like it. This is no longer the way to build it, so we can now simply add in TheRepository as the second parameter. And we’re doing this in the BaseApiController so that we only have that one place that we’re creating this and using it. So, let’s go back to our DiariesController where we had the Post. Let’s say that if the entity equals null, we can just do Request.CreateErrorResponse.BadRequest, “Could not read diary entry in body”. So we couldn’t parse it, so we’re going to give them some sort of error that lets them know that the error is in the body of the message that was sent. You could be more clever about how you let them know that. Now, we’ll simply go ahead and get a diary, and we’ll get that from TheRepository. We’ll get the diary by first passing in the identityService.CurrentUser and then our diaryId, just like we’ve gotten the diary before. And if the diary equals null, then we can then say Request.CreateResponse StatusCode NotFound. So, we’re trying to add an entry to a diary that doesn’t exist. And lastly, we just need to say diary.Entries.Add(entity); TheRepository.SaveAll. So now that we’ve supposedly saved it, again the Exception is going to catch it if the Save doesn’t work, and the adding of the entity to the entries doesn’t work. So, here we can successfully just say return.Request.CreateResponse HttpStatusCode.OK, except that in the case of Post you shouldn’t return OK, you should return Created. Post has a relationship with the StatusCode to say we actually created an entity here, therefore I’m going to return a 201, which is the StatusCode for Created instead. But, we should also return the new entity. The reason for this is the database, as it builds this and it adds it, it’s going to do things like specify the new ID correctly, so that the data we’re sending back is the fully formed version of that diary entry. So, we’ll go to TheModelFactory and Create our model from our entity. Let’s see if I did everything correctly, and let’s try to actually Post it again. Again, same data. Execute 201. And in the body of the result is going to be the JSON that represents the actual data. Here’s the foodDescription, Acorn Flour; measureDescription is 1 Oz. There’s the URI for the entire measure, as well as the quantity we had specified, and the URL of the new object, which is 19. This way they can take the new object that was passed back, and actually just use it as a fully formed object instead of assuming this missing data, or just having it null. They’re getting the actual object that they then can use to go ahead and Post updates, or delete it later if they need to. But this would mean that we could go ahead and add a new element into that collection that was also the same nutritional information. What if they ate more Acorn Flour, or maybe the user of your API is confused, because what we want to see in a daily diary, let’s say one of our business rules is that a diary only contains the same food once, so that if you eat 2 pats of butter at breakfast, 1 pat at lunch, and 8 pats at dinner, that you’re going to have a total of 12 in that diary instead of 3 separate entries for butter. This may or may not be the right solution for building a website, but let’s say that’s our business rule. Right here in our code is where we’re going to want to test that. So, let’s say we’ve got the diary, and before we go ahead and Save the new Entry, let’s make sure it’s not duplicate. And we can simply do that by saying if diary.Entries.Any, and we use a little link here to say if the Measure.Id equals the entity.Measure.Id. So if the measureId of any of the entries that already exist equal the measureId of the entity we’re about to insert, let’s go ahead and throw an error, and then I’ll just give them a little string that says Duplicate Measure not allowed. Let’s go ahead and re-execute our same insert to see whether we are going to get this error. Yep, 400, and then the JSON message that is returned has that message in it so that they can show it to the user, or determine from debugging that something is in fact wrong. One of the problems that may crop up is adding this diary entry in may fail without throwing an Exception. So, we really should be checking whether the SaveAll, because it returns a bool, has succeeded before we return our Created StatusCode. And let’s go ahead and put an else in there, and just return a BadRequest. In this case, I’ll say “Could not save to the database.”, so that then they know that something awful has happened. And right now, this Post is working just as we expected it to, but one thing that I don’t like is that early on we had decided to return an object, which, of course, now that we have built it, we know we want this to be a ResponseMessage, because in every case we’re returning a ResponseMessage. It may be only a Status ID, it may be a Status ID with some state, or in the case of retuning the Created, returning the Status ID plus our new model. Make sense? Implementing DELETE

So, now let’s implement the DELETE method. We head over to our code. We’re just going to create a new method, and I’ll do this after the Post we just created, and let’s go ahead and create public method, and go ahead and use ResponseMessage as a return type. And, we’ll call this Delete, and like our other methods, we’re going to need a DateTime to specify the diaryId we want to Delete from, and we’re also going to need the ID of the individual entry we want to delete. So, like before, we’ll go ahead and use a try/catch to just return a BadRequest, with some Exception information. We’ll do the same thing we did in the Post. So, first we’ll want to determine if this entry exists or not. And so we can do that by simply saying if TheRepository.GetDiaryEntries, go ahead and pass it the Identity information again as the first parameter, and then give it that diaryId as the second parameter, and we’ll go ahead and use that Any again to simply say, if the entry Id equals the Id, so if the ID of any of these entries match the ID that was being passed in, and we can’t find it because of it’s returning a false, that Any call, then we can go ahead and say Request.CreateResponse in this case because it’s not an error. This might be something they’re actually using that is valid, and it’s not found. We’re just returning a 404 essentially, because we can’t find the ID you’re trying to Delete. Now that we’ve made sure that the ID actually exists, let’s go ahead and Delete it. If TheRepository.DeleteDiaryEntry, and we give it that id, and TheRepository.SaveAll, the Request.CreateResponse, it’s all OK. Else we’ll just return a BadRequest, because this means that we failed to Save the data, but there wasn’t an Exception, so we can’t really give them any more information than it was a BadRequest. And, of course, putting in all these requests, I actually have to return. Sometimes I miss the forest through the trees. Let’s go ahead and compile it again, and let’s go over to Fiddler, and let’s put together a Delete. When we change this to DELETE, you’ll notice that the Body becomes red because you can’t have a Body in a DELETE. It only allows Headers and then the URL. And, in our case, let’s go over to the browser for a minute, and let’s look at our entries for this diary again. And down at the bottom, you’ll remember we created two separate Acorn Flour ones, and obviously we don’t need both, so I’m going to Delete this one. I’m just going to Copy the URL here, and this is just going to the URL to the specific entry. Let’s clean up the Headers in that there is no ContentType or ContentLength, because there’s no actual content, and let’s go ahead and Execute it. Again, all you’re doing is giving it the URL with the date of the diary and the ID of the entry that you need to set, and you’re just calling DELETE, that’s all the data that’s really requested for this kind of request. 200 means it’s gone and if we Refresh in the browser, you’ll see that 19 is now gone. If we repeat this for 20, we’re getting a 200 again, and now 20 is gone. If we try to Execute this again on 20, we’re going to get a 404, because it couldn’t find the item for 20 anymore, we had already deleted it from the database. So, now we’ve gotten DELETE working, and we could repeat this process with different parts of our API. Implementing PUT/PATCH

So now let’s talk about PUT and PATCH. So, typically when you want to update a resource through a REST API, you would use the PUT method to do this. So, let’s go over to Fiddler and just sort of craft this so we can see. The PUT method would allow you to take a specific diary entry, let’s say 15. You could go ahead and craft a JSON that represents the update we want to make, but the spec is very specific about PUT. It expects the PUT to be the entire object. So, that means we would’ve had to retrieve the object, made our changes, and then put the entire object back, which is probably fine. But in the case of ours, we want to also support partial updates. But, really the only thing we’re allowing them to update is the quantity, and so in our case it’s actually the same in either case. So, let’s go ahead and implement the method for it. Back in the controller, we can create a public method, we’re going to return ResponseMessage as usual, and we could certainly do Put, take in the standard DateTime id, and in this case we’re going to need the id for the individual object we’re changing, because we’re talking about supporting change on an individual resource, in this case a diary entry. We’re also going to need the actual content from the body of the message. This is going to be a DiaryEntryModel. This is going to be the new data that we’re going to update it with. And let’s go ahead and play catchup with our try/catch, just using some editor inheritance there to do the same thing. We can go ahead and implement the Put here. The reality is for our case, because we’re only asking for what can be updated, in our case, the quantity, Put may not be the right thing. Because, if we’re going to implement it by the spec, only allow us to specify the entire object at once, and that’s just not necessary for us. So, we’re going to instead implement a newer verb that is supported by HTTP called Patch. Patch allows you to send a partial object down and apply it. So, here in Patch, let’s go ahead and try to get the entity that represents the data in the data store, or TheRepository. Let’s go ahead and get the DiaryEntry, and here we’re still going to need to pass in the identity, the diaryId, and then the id of the element itself. It’s asking for all of these because the ID has to exist inside a diary that is then owned by the current user. If the entity equals null, we can go ahead and do a CreateResponse NotFound. So, we can’t update it because, as far as we’re concerned, it doesn’t exist. And this might not exist because the ID isn’t there, but it also might be that the ID doesn’t exist in that diary, or the diary isn’t owned by this person. Now that we have the entity, we’re going to want to get the parsedValue by calling the TheModelFactory.Parse to go ahead and get an instance of the entity that contains the data that is new. In our case, the only thing that matters whether it’s new or not, is if the entity.Quantity does not equal the parsedValue.Quantity. And we’re taking a leap of faith here because we’re assuming parsed quantity isn’t null, so, of course, let’s go ahead and do the same thing we did here, except return a BadRequest. So, if TheModelFactory returned us a bad parsedValue, then we’re going to- there I go forgetting return again. We’re going to break out of this method by returning those responses. So, now we’ve gotten to a point where the entity is different. So, let’s go ahead and say, entity.Quantity = parsedValue.Quantity because, again, that’s really the only value we’re going to support changing or patching, and go ahead and check that TheRepository.SaveAll. And in this case, we can go ahead and say, return Request.CreateResponse, and we’ll return OK. And then down here we’ll go ahead and just have a fallback. So, if the response wasn’t OK, we’ll go ahead and return Request.BadRequest. So, let’s go ahead and build that. And let’s go ahead and craft in Fiddler what we need here. Because the quantity is the only thing we really need, let’s go ahead and find one of these to update. So, let’s do this number 15, and update the quantity from 1.5 to 3. There’s 15, and if we Execute it, we’re going to actually get a Fail response. And that’s because we changed the method from Put to Patch. So, let’s go ahead and pick PATCH in here, and it has the same behavior. We’re going to need to tell it the ContentType as well, and now we’re going to get a 400 error. Now why did we get the 400 error? We could DEBUG it, but the reason is that we’ve assumed that Parse here was going to work. Let’s walk into Parse, and let me show you why it isn’t. In Parse, we assumed that the URI for Measure was going to valid. We assumed that the MeasureUrl was not going to be blank. But in our case, we don’t really need it, so what we’re going to want to do is just protect that by saying, if model.MeasureUrl it’s not empty, or just full of WhiteSpace, then we can go ahead and Parse that. This means that in some cases, in fact, in our case, we’re going to attempt to Parse it, and we’re going to Parse it down to not including the food or the measure in cases we don’t really need it, like this. Because it’s going to Parse, it’s going to get the quantity, because the quantity is the piece of information we really need. In our case, the rest of the data we need is actually sent here in the URI as the diaryId, and the ID of the element we’re looking for. The fact that we’re not getting the food isn’t all that important. We certainly could have a business rule that required the measureId so that we could make sure it was on the same food, but in this case I don’t think it’s that important. Being able to just update the quantity is probably good enough. So, now that we’ve made that change, let’s build it, and re-execute it. Now, we’ve got the 200. If we go back and look at the data, we should see this turn from 1.5 to 3. We change this to 7.75, and Execute it. We can see it’s 7.75 now. So, we’re able to update data using our API using the Patch. You may want to support Put and Patch using the same element. If you wanted to support Put and Patch, and have one method really handle both of them, the trick there is to actually add attributes. Putting this attributes on the method tell it that these are the two verbs it’s going to use. By using the attributes, you’ll telling it to not infer it by the name, but simply to use the attributes as the designator of what verbs are going to call this method. So, if we come back here and change it to PUT, and of course change the quantity because we have the test in there to only update it if the quantity has been changed, you can see that PUT also works because we’ve included the attribute of Put and Patch on here. So now we have all four logical verbs implemented on the DiaryEntriesController. We’ve got Get, Post, Delete, and Put and Patch, which are really logically sort of the same operation. Let’s talk about Paging. Implementing Paging

So, next let’s talk about Paging. If we go back and look at the FoodController, when we return these values, we’re not returning the entire collection. We’re not returning the entire collection because returning 4 or 5000 items is almost never a good idea. So we implemented this in the FoodController by using Take. Take is a Query method that says only return the next this many items. So, in this case, I’m only returning the top 25 items, which is why all of our food started with A in our particular case. What we’d like to do is support Paging here, so let’s go ahead and start by adding a new parameter called Page, and I’m going the make sure that if it isn’t supplied, that we’re using and returning the first page. We’re also going to need to know what the page size is, so let’s go ahead and create a PAGE SIZE of let’s say 50. This means in the Take, we can just go ahead and say we’re always going to return that same PAGE SIZE. But, in order to use Paging, we’re going to also want to use another query parameter, called Skip. Now the way you do Paging may differ based on how your repository is structured, and where your underlying data store is. Because TheRepository is returning IQueryable, we can just use Link in order to handle the Paging for us. This means that when we want the first page, we want to skip no elements, but in each successive call for a page, we want to skip the number of the page size times the number of pages. So, we can simply say PAGE SIZE times page. Because we’re going to 0-based, the 0 page times PAGE SIZE is going to be 0 for the first page, so it’ll skip 0, and the next time if we say page 1, we’ll skip the first 50 and then Take and Display the next 50. Let’s compile this and see how well this works. Here in our Foods, when we Refresh it, we’re just going to get that first page. It’s actually going to return more than we used to, because we’re returning 50 elements now. But if we add Page=1; before I Enter this, remember that Abalone is the first element here, but when I go to page 1, I’m now getting further down the list, Alcoholic Beverages. Or if I say, Page 100, I’m getting Papaya Nectar. And if I say Page 1000, I’m not going to get anything because we end up skipping the entire collection. So, if someone asks for a page too large, they’re simply not going to get any results. Unfortunately, this doesn’t really solve anything, because we can support paging, and we can tell them through documentation that Page is supported, but we’re not really giving them a sense of how many pages there are, and how many results there are total, which ends up being important in the whole paging story. So, let’s go back to our code, and let’s figure out a way to do that. Let’s go ahead and Copy results down here, and let’s call this our baseQuery, and the baseQuery is going to be just the OrderBy. All the other work is going to be when we actually Execute the query here. And the reason for this is we want to be able to get some counts. So, let’s say totalCount = baseQuery.Count. This is going to return to us the total number of items that are available to us from this query. The next thing we can do is get totalPages, which we can do by calculating the totalCount, divide it by the PAGE SIZE. And we’ll use Math.Ceiling to make sure that we get one more page than we actually need, so that the last page is that partial page. Then comes the question of how do you actually return this in a way that is useful to the users? Some people will return this as HeaderValues, but in our case, I like to send this as a wrap around our collection. So, we can do this by changing the return type, in this case, just to an object, and what we can return is just a new anonymous object that will get serialized into JSON for us, and I will call this Results, which will be the array that is the actual results. I’ve been doing JSON too much. It’s equals and then I’m just going to add TotalCount and TotalPage = totalPages. And because, we’re returning this anonymous type, When we look at this, we’re now being fed the information that might tell us a bit more about the operation. This is the total number of pages, so I should be able to go to page 150, and remember our page number is 0-Base, so the last page is 150, and see the very bottom of the list. Zwieback is the last entry. If I go to 1, we should get no results. Now that puts us pretty close to something that’s useful, but I want to introduce the idea of adding even more helpful information here. And, so let’s add two URLs. In fact, let me reverse the order of those. Let’s go ahead and compute those. In this case, we want to go ahead and create new URLs that are going to be able to be accessed immediately by using them to get the previous page and the next page. So, before we can create these, let’s go ahead and create a helper. We don’t actually have a helper as part of the BaseApiController. We could certainly do that, but it doesn’t come up that often, so I’m going to go ahead and just build it by hand, and make sure I get the one from HttpRouting, not the one from MVC, and pass in our Request, which is, of course, required, and we’re going to use it here to create our prevUrl, which will be helper.Link, and the route name is going to be Food because that’s the name of our Route, and then the values are going to be page, and we’ll do the same thing for next. Of course, this needs to be new. Object that represents the collection that contains our page. So we’re simply just going to construct some URIs that are based on what those page values are. Of course that these both don’t actually help if the page doesn’t exist. So, let’s go ahead and say, if page is greater than 0, use the helper; otherwise just make it an empty string. Same here, if page is less than total pages -1, because again it’s 0-based, then we can create a next one, otherwise we’ll give it an empty string as well. And if I’ve done this right, which no promises, we should be able to take these computed URLs, include them in the return so that the user of our API can see that there’s no previous URL, but the next one is page 1, and as we click through, we can see the previous and next page. We could give them a first and last as well if you feel better about that, but this is usually good enough. And this simplifies what a user will have to do with your API to simply walk through that collection. So, if they’re showing this in a grid, or something like that, they have the pieces they need to be able to show the data as the user asks for the next page, the next page, the next page, etc. You could certainly make this fancier by allowing them to include a PAGE SIZE and to throw ERRORs if the page size is too big, those sorts of things, but this should get you on your way to the type of things you’re going to want to do. And I think it’s certainly fine that in some occasions to return anonymous types as long as they don’t represent the actual entities you’re producing. We’re never going to produce something that looks exactly like this, but we certainly could. We could create something like a paged result that knew the collection of Results that was inside of it, and then knew how to do all these computation for us. We could centralize that, but this should get you as far as you need to go. One more topic for this module. Let’s next talk about RPC-style calls. Implementing RPC-Style Calls

Lastly, let’s talk about creating RPC-Style Calls. And when I’m talking about RPC-style calls, I mean ones that are execution-based rather than resource-based. It may be that you want to insert something, or you want to cause some action to happen. It’s not just about data, but it is about action. In our case, let’s go back to our Visual Studio project, and let’s create a brand new controller. And I’ll call this our DiarySummaryController. This would be a simple controller where we can do a Get against an individual diary date, and then Get a simple object that’s going to represent the summarized data for an individual diary day. So, let’s make some of our standard changes here. Add a constructor. We’re going to need to supply some basic information, and so I’ll actually Copy this from our DiariesController, bring in some namespaces, and so now we have basic construction of our DiarySummaryController. Let’s go ahead and create a public method that’s going to return a new object that we’re going to call a DiarySummaryModel. It’s going to be the data that represents an individual day of data. And like our diary, we’re going to use the same diaryId to compute that data. And so let’s go ahead and do two things. First, let’s go ahead and Create our model. This is going to be just another Class, and let’s go ahead and just add a couple pieces of information, like the DiaryDate let’s call it, so we have the date of that diary, TotalCalories. Because our other models are only returning calories so far, giving it the TotalCalories is fine. Later on we may return more nutritional information, like calcium, and protein, and fat, and sugar, and those sorts of things, and so this will be an object that sort of represents the total amount of that sort of data. Now that we have the model, let’s include the namespace. We’re also going to need to add in a Route for this. Let’s go over to WebApiConfig, and let’s make yet another Route. In this case, I’m going to Copy the Diaries Route. It already has the pattern I want. But in this case, I’m going to call it Diary Summary. So notice what we’re doing is we’re pretending that it’s actually a part of the diary resource, but we’re just adding another association that is just going to be a simple association that’s going to act like an RPC or a method call, called summary, that will return us the data we want. And I’ll make sure that’s the DiarySummaryController, and in this case, the diaryId is not Optional, so we can just get rid of that. There are no other parameters. We’re always going to get the summary for an individual day. So, the first thing we’ll need is the actual diary, and let’s go ahead and put a try/catch around it to be good citizens. And, because we’re going to do try/catch, we can go ahead and just make sure that we return our HttpResponseMessage, or, if you want to be a little looser, you can actually return an object, and if you do have a catch, you can always say return Request.CreateErrorResponse. (Typing) And this way we can actually return our model summary type if we have success, otherwise we can use the CreateResponse, or CreateErrorResponse for exceptional cases later. So, let’s use TheRepository to Get our diary, diaryId, but to null, then we can go ahead and return the Request.CreateResponse NotFound. Sort of quickly going through this because a lot of this is a repeat of what we’ve done before. And then finally, we want to be able to produce a diary summary, so I’m going to say return TheModelFactory.CreateSummary in our case, and we’re giving it a method name instead of just saying Create, because the creates are really to map an entity type to a model type, and so we’re using the fact that we could overload that to sort-of marry that. So, I need to give it a different name, and CreateSummary is fine, because we might have summaries of other types of operations in our API. Of course, CreateSummary doesn’t exist, so I’ll generate the method stub, and then let’s go navigate to it and make it work. And returning it’s fairly simple. We can just Create a new instance of a model. Say the DiaryDate is going to be diary.CurrentDate, and then TotalCalories is just going to be diary.Entries.Sum. Now the Sum is going to be the Measure.Calories times e.Quantity. So we’re going to just do the calculation to get the TotalCalories here. Let’s go over here and go back to our user diaries. There’s a diary, and if I just add summary to it, we’re now getting the operation it’s going to return of some data. This means that TheModelFactory is also going to be the place I am going to do some formatting here. So, I might not decide that hundredths or thousandths of a calorie matter on a daily basis. So, it’d be fine for me to just say, Math.Round to make that nice and pretty. So, in this way we can create endpoints in Web API that really are functional operations. They are much more like Remote Procedure Call, but because they’re inside REST, we still want them to be without side effects or without state. We want them to be as stateless as possible. So, you can see that this summary is doing those calculations and returning it, and it might even, if those calculations were expensive, decide to Cache it, but we’re not going to really handle changing state in these RPC-style calls. That’s what the resources are for, and we should stick with those. I wouldn’t do things like Insert Invoice, and have those invoices then do that operation, including the changing of the data. There are times when RPC operations might be useful to kick off certain things. Let’s say, kick off the rebooting of a server, or sending a text message, where the data you’re returning may just be failure or success, or even something like _____ with a ticker to come back later and check to see whether the operation, asynchronous operation is complete. So, using Get, or Post or any of the other operations to create RPC-style calls is okay, but they should be the exception. This is a good example, in my opinion, because we have the difference between handling the resources to manipulate data, and something that is more functional in nature. And the mix is about right as well. I found that in most projects I’ve worked on with REST-style interfaces that a majority of the work is being done in resources, and then there’s always those one, two, or three small little extra pieces that more fit into an RPC style API. I don’t mind mixing them because I want to be pragmatic. Again, trying to get the actual work done, I’m willing to bend some of the rules of REST in order to do that. Let’s wrap it all up. Summary

So, just to summarize what we’ve been talking about in this module, Web API allows you to build REST-based APIs in a pretty succinct way. They want to match the REST-like operations to the API. We are not trying to sort of mimic what is HTTP and using verbs in HTTP to some other sort of mechanic. The controllers themselves are exposing the same verbs that HTTP can. Implementing associations is simply the matter of creating new controllers that are associated with other controllers, and this association is really built into the Routes for those specific entities. Instead of implementing IDs, implementing URLs so that the users of your API not only know maybe what the ID is, but more importantly, what the URL to the resource is. It can really simplify the usage of the API instead of having to teach them how to build the URLs that you are going to respond to. You can complete your API by including the ability to insert new data, to change data, and to delete data, by using simple HTTP verbs on your ApiControllers. If you need to be able to post to your API, creating a method called Post will do that. Same for Delete. Same for Put. Same for Patch, in addition to other verbs as well. And finally, being able to take your APIs and support Paging means that when you’re dealing with large amounts of data, that you can give your users the ability to be able to get that data in a way that makes sense and is quicker, and it also allows you to protect yourself from accidentally returning much larger amounts of data than the user can actually use in their scenario. This has been Module 2 of Implementing Web API. My name is Shawn Wildermuth. Thank you. Securing APIs Introduction

Welcome to Module 3 of Implementing an API in ASP.NET Web API. My name is Shawn Wildermuth with Wilder Minds. In this module we’re going to be talking about securing the API itself. We’re going to start by talking about APIs and Security, Cross-Origin Security, Authentication versus Authentication. In addition, we’re going to discuss User Authentication versus App Authentication, using ASP.NET Authentication in Web API. We’re going to show you how to build Basic Authentication, Token Authentication. We’re going to walk through an example of OAuth. Let’s get started. APIs and Security

So, in securing a Web API application, you’re going to want to think about what in fact needs to be secured. And the amount of effort involved really has a lot to do with how sensitive the data is. The value of sensitive data in your system is directly related to what kind of data it is. You may have statutory limitations. So, if you’re doing something like a medical system, you can be liable for large fines if there’s a data intrusion. You might have financial data, like credit card numbers, so if you’re running something like an Ecommerce site, or a clearing house, you’re going to make sure that that data is very protected. Or even something as simple as writing an order entry system for a pizza shop. You might not think that that needs to be very protected, but you still need to make sure that the sensitivity of the data that’s being transmitted is safe, especially when there’re financial instruments like credit cards being processed over the wire. So this comes down to a question about what needs to actually be secured. This is a small discussion we had in my Designing a Web API course here at Pluralsight, but I’ll bring it into this discussion as well. If you’re writing an API that’s using private or personalized data, you need to secure it. If you’re sending any sensitive data across the wire, like credentials, address, phone number, social security number, credit cards especially, you need to secure it. If you’re handling credentials over the wire in any way, you have to secure it. And if you’re trying to protect your service from overuse from denial-of-service attacks, and just intrusions, you’re going to need to deal with security as well. And not all of these can be handled at the API level. Doing some basic threat modeling to understand where the vectors of security problems can happen is important when you’re trying to secure your Web API application. So, of course, we know we have users that are going to use your API through an internet connection ordinarily. This may be an intranet connection in some cases, but the same problems exist in both cases. And, of course, you have your servers that are normally protected with physical network devices, like firewalls. Threats can some across the spectrum of operation. You can have eavesdroppers that are listening to the traffic as it goes along looking for sensitive information. You can have hackers that are trying to do forced intrusions through those devices, like firewalls, but you also have personnel that could be doing various things with that data. And you have users and hackers that are trying to get at the data, find holes in the JavaScript code for a website, or that are trying to intrude across the internet. So, you have to understand that problems can come from all these different places, and there’s different ways to attack each of these security concerns. It’s outside of the scope of this course trying to handle everything, like location security, understanding intrusion detection. We can’t really handle that, but the API, once we understand where we can protect a lot of this data, we can do some things in Web API to support that. So, at the end of the day, you need to protect your API. Securing your server infrastructure is outside the scope here. We’re going to assume that you have armed guards, and key codes, and everything they have in the movies to protect your servers from people actually getting to the physical boxes. You will have to worry about secure in-transit, and so as you communicate information from the client to your servers of stopping those men in the middle from looking and sniffing at those packets. This is typically done with SSL, and SSL is almost always the right thing to do. The weight of processing SSL in the client and the server is small compared to the level of security you get in that transmission. And the cost of actually implementing SSL, the processing involved in encrypting and decrypting information on both sides, is usually worth the expense. You may find some situations where the CPU cost is prohibitively high for doing this, but in today’s day that just doesn’t happen very often. You also need to worry about securing the API itself. So, securing it from other websites trying to use the API, so whether to enable to disable cross-origin security, and then typical authorization and authentication, which we’ll talk about at length. Requiring SSL

So, let’s talk about how to support SSL. If we come back over to Visual Studio, we’ll see that we have the solution pretty much as it was at the end of module two, with the exception that we’ve actually implemented a couple of the operations on our API that would’ve been duplicative to show you. Specifically, this was the Post and Delete on the DiariesController. If you want to follow along, you’ll want to go get the after from the module two directory of the examples if you have access to them. So, we want to have a way in our Web API to force the website to use HTTPS. Now, it may be that you’ve already configured this on the server, and you’ve already installed certificates on the server to support that. I’m going to assume that you have already figures out how to get certificates onto your IaaS server, and that you don’t need help with that. There are some other videos here on Pluralsight that could help you with that. That’s outside the scope of what we’re trying to do here. We want to talk about cases where we want to make sure that Web API itself uses HTTPS even if the server isn’t configured to force it on the entire website. Best case scenario is that you’re just going to support it on the entire website, but there may be cases where you’ll want to just apply it to either the entire Web API, or individual operations on the Web API. The way we do this is with filters. Now, in Web API, there’s this notion of something called a Filter. This is an attribute that you can apply onto parts of the Web API project to say that when this item is processed, this is going to be some code that is going to be called during the pipeline of the request. So, by creating a Filter, we’re going to have the opportunity to be called during the processing of the Web API request. The particular type of Filter we’re about to build is going to be called before the actual Web API code is executed. So let’s Create a new Class, and let’s call that RequireHttpsAttribute. This is going to be an attribute that we can then apply to either parts of our Web API, or the entire set of Web API calls to force it to require HTTPS. And, in our particular case, we’re going to tell it to reject the call if it’s not HTTPS, and give some header information to tell browsers to go ahead and switch to HTTPS. In order to do this, we need to derive from a Filter base class. They all implement an interface called IFilter, which is in the System.Web.HttpFilters, and this Filter is just a simple interface that all the real functionality is derived from. So, instead of implementing IFilter ourselves, we’re actually going to use AuthorizationFilterAttribute. This is a filter that’s going to allow you to get called when a particular call is about to be authorized. So we can override the OnAuthorization call. And this OnAuthorization call is expecting us to either allow the call through by simply returning through, or by injecting into the response creating a new response that is going to say that something is wrong, most notably, not authorized. This actionContext is a class that contains different parts of the actual operation. Includes access to the request and response object so that we can read what the request is to make decisions about the response. And that’s, in fact, what we want to do here. We want to look at the, let’s go ahead and get the request out. We’re going to look at the RequestUri and look at the Scheme to see if the Scheme is HTTPS. We can test with the constant of Uri.UriSchemeHttps. If it doesn’t equal HTTPs, we’re going to want to present to the user just a tiny piece of HTML that represents that something is wrong. And, so I’m just going to create a little html string here that says https is required. So, a tiny piece of markup that we’re going to include in the response. What we do here is going to be different whether it is a GET or a non-Get request. So, let’s go ahead and ask if the req.Method.Method, which is the string of the method, don’t ask me why it’s Method.Method, I’m not a huge fan of the way they do that. If it’s a GET then we’ll do some work. Otherwise, we’ll do some other work. And so let’s start in the else first. Here we can simply say actionContext.Response = req.CreateResponse, and notice it’s not showing up in IntelliSense. That’s because we’re actually missing a namespace declaration where the extension method for req.CreateResponse is included, and that is System.NET.Http. We include that, then we can now see that we’re getting IntelliSense for the extension method of CreateResponse. And we’re just going to want to set the status here, and add that namespace of System.Net to NotFound. And then we’re going to need to set the Response.Content to that string that we created with the HTML. So, we’re going to say new StringContent. We’re going to pass in HTML as the string of the content. We’re going to give it an encoding, let’s bring that namespace System.Text in, and UTF8, and then the media type for HTML is text/html. By doing this, it’s going to set all the appropriate headers on our response for us. But, again, remember this was only if we weren’t doing a GET. What we’re going to do for the GET is pretty close to it, but the status code we’re using is actually a little different. It’s going to be Found. So someone makes a Get request, and if they’re using HTTP, we’re going to say, hey, we found this. This is a valid URI, but we’re going to give you some more information about where it’s actually found. So, this is different than OK, in that it’s going to tell browsers and other people interested that where the object is located is under HTTPS, not under HTTP. Now, that we’ve created the response in the content for Found, we also want to include one more piece of information, and to do that we’re going to create a new URI. So, let’s go ahead and create a UriBuilder, which is a class that will allow us to put together a URI, and we’re going to pass in a URI as the base of the new URI, and we’re going to get that from the request. We’re going to use the RequestUri as the basis for our new URI. So, we want everything that is inside the existing request that they’ve asked for, but we want to make a couple of changes. So, we want to go to the Builder, and say, the Scheme is going to be Uri.Https. We’re changing it from HTTP, or whatever scheme it was using, to use HTTPS instead, and then we can do the same with Port, by specifying that it’s going to Port 443 or the SSL Port. Now that we have the URI ready to be used, we want to use it some place, and what we want to do is go to the Response.Headers, and there is a header called Location that we want to set with this new URI. (Typing) Let’s see if that builds. Yep. And, now that we have the attribute built, we want to use it. We want to put it on different objects to specify that we want to require HTTPS in certain cases. So, let’s open up the FoodsController for a minute, and we could actually add it here. We could just say RequireHttps, and this would inject that Filter into the pipeline when we’re making any calls to the FoodsController. We’d know that if I’m doing a GET on Foods to go ahead and call this OnAuthorized first. It may be that you want it on some controllers and not on others, or even on some methods and not others. In the case of RequireHttps, we actually want it for the entire Web API. So, instead of trying to make sure that we haven’t messed up by missing it on a controller, we can actually add it directly in the Web API configuration. Here at the end, we can simply say, config.Filters.Add and create a new instance of our Require Attribute, and in this case this will be added to the standard set of filters for every single call coming into Web API. So, this is really common to make sure that your API is using SSL so that regardless of the kind of data you’re dealing with that you’re going to be using SSL in all cases. Let’s see this work. So, I’m going to pop over to Fiddler, and let me actually Copy the web address here for our project, and let’s go ahead and navigate to any of our APIs. So, I’m just going to go to NutritionFoods. And if I just issue this GET against our food API, we’re going to see a couple of things happen. Our call to FoodNutrition is going to give us a 302; 302 is found in HTTP status codes. So Fiddler found our Foods because what we did was we actually returned that we found it, and then we returned the Location as the new location. And, notice the only difference is its HTTPS, and we can also see that that body of the message was sent back as HTTPS is required, so that if this were shown to an actual user, for we’re doing this directly in the browser, that they could actually read that. It wouldn’t be a very pretty page, but it serves the process. But, because we set 302, the browser will do the same thing that Fiddler is attempting to do, and that is immediately issue the call to HTTPS. It took that location header; let’s look at Raw, and it attempted to find this. Now, we don’t have HTTPS configured on our test server, we’re just using IaaS Express, and you can set that up to use a locally signed certificate and such, I haven’t set all that up because that can be a little cumbersome, but I just wanted to explain what was going on. So it’s attempted to get this, and then it’s rejected, because there is no one listening to 443 on this particular machine. And the same thing will happen in the browser. If we head over to Firefox, and we go ahead and put in an API for NutritionFoods. It’s showing us, to the user, not that HTTPS is required, but, in fact, it’s showing us an Unable to connect, and why is that? Because, when we requested it, it actually switched us over and changed the URI to the HTTPS because it got the FoundHeader, plus the location, so it knew where it was supposed to be located at. Normally, when I’m building an API, I will do if not DEBUG, so that this isn’t actually turned on in my test builds. I can go ahead and go about the business of testing my application without any SSL, but then once this is built and deployed on staging servers, and test servers, and ultimately production servers, that this rule will be then enforced. Make sense? Cross Origin Security and JSONP

The next thing to concern yourself with is cross origin security. The concept here is that you want to be able to support calling from other domains. If you’re implementing in API, and you want to use it from your own website, that works fine with Web API. But, if you need to call it from other domains, if you have other websites that you want to be able to call in and use your API, straight from JavaScript on their pages, that’s not going to work. And so there’s a couple of ways you can get around this. First is to support something called JSONP as a format. JSONP allows you to wrap the response of a call in a small piece of JavaScript to ensure that when it’s called back, that that JavaScript is executed. Because JavaScript files can be called from multiple domains, browsers typically allow this, because JSONP comes across the wire as Application/JavaScript. The other way is to use something called Cross Origin Resource Sharing, and there’s some support for this coming in Web API 2, but we’ll show you in a minute how that’s going to work. But, let’s start by supporting JSONP itself. Back in Visual Studio, we’re going to want to support it as a new type of formatter. We want to actually Add support for JSONP, so that when people request JSONP, we can actually return it. It’s just another format. It’s not anything we have to support into controllers themselves. Now, in Web API natively, there’s no support for JSONP, but there is a project out there called WebApiContrib, which actually has implemented JSONP as a formatter. So, we’re going to start by going out to NuGet, and you can get to it by searching for webapicontrib jsonp, and it’s the WebApiContribFormattingJsonp package. I’ll go ahead and Install that in our project, and it adds a quick reference to this project. Then we can simply add the support here. We’re first going to create the new formatter by calling new JsonpMediaTypeFormatter. You can see that this is in the WebApiContribFormattingJsonp namespace, and this is going to lean on another formatter, one that does JSON itself. Since we have already used the configuration for jsonFormatter up here, we can just go ahead and include it in here. And, then we’re just going to add it to the configuration, Formatters, and we’re typically going to add it as a first formatter. The reason for this is the standard JSON formatter will look at Application/JavaScript and go ahead and return plain old JSON. We’re going to get in there so that if someone asks for it, we’re going to serve the Application/JavaScript formatting for them, and if it’s not that format, it’ll drop down and use one of the other formatters that matches it. Let’s see if we Build, and let’s head over to Fiddler, and let’s go ahead and Execute this Foods. When we Execute the Foods, we’re getting just the standard JSON format by default because we don’t have an Accept header. Without an Accept header, it defaults to JSON. We could certainly ask for application.json to specifically ask for the type of data we want, and we’re going to get the same response. But what if we change this to application/javascript? This is going to just return the JSON version because we haven’t included a callback. So, let’s talk a little bit about how JSONP works so that you can get a sense of it. When we ask for a JSONP Request, the call to this API is going to attempt to callback into your JavaScript code when you receive it with a method call. So, essentially all that JSONP does is wrap this result, this JSON object, in a small piece of JavaScript that calls a function that you have implemented. And, so we need to be able to tell the API that there is a query string parameter that’s specifying the name of that callback. So if we add to our URL callback, which is the default query string name, and I’ll just say foo, when I Execute it, it actually just adds this quick little foo at the beginning and all the end at the end is going to be, if I can find the end, is an end parentheses. When jQuery Ajax is used, or maybe Angular is being used, when it sees that this is the data type that’s coming back, it knows to parse it, and in that parsing, it actually executes this method call. This method call says, call if function called foo, which the author of the webpage would have written to accept that data. So, really all that JSONP is doing is getting around it by pretending that we’re downloading a piece of JavaScript to be executed, not pure data. Now, we can change the name of the callback here in case you are already using this query parameter, and we can do this in the construction of the formatter itself. The second parameter can be the name of the callback, so if I say, cb, because I want something nice and short, then we have to make sure that our callback here, cb, that it works as well. Because, again, we specified the name of the callback function that we’ve implemented that we want the JSONP to callback to. So, supporting JSONP is pretty straightforward and simple because the WebApiContrib people have helped us. Supporting CORS

The next piece is to support CORS, or Cross Origin Resource Sharing. So, there are a number of techniques of doing this, and if you search out on the web you’ll find a number of them, but I wanted to introduce new support for it in Web API 2 in a way that I really like. I’m not going to show you in the actual project, because we’re only using Web API 1, because that’s the only one that’s been released, but let’s see what it actually looks like. It allows you to just opt into CORS support out of the box. It’s not a configuration anymore. It’s not writing filters. It’s much simpler. And the idea here is that when you configure Web API that you can simply say EnableCors and include a special EnableCorsAttribute if you want to support it on the entire API, much like we did with the RequireHttps. We can also apply it to a per-controller, or even per-method, in the same way we supported RequireHttps. In that case, we would still have to call EnableCors to turn on the function in configuration. In this case, we would still need to call EnableCors, but with no parameters inside of our configuration, but in our controller, we can add it to the controller itself, or even to individual methods if we want that level of granularity. And we can use the DisableCors attribute to turn it off in specific cases. So, we can simplify it by saying let’s enable it everywhere, and then turn it off in a couple places where we don’t want the API to be used by anybody but our website. So, we wish this were all available now, but it’s not, so you can look forward to the Web API 2. You can actually use this in existing code today, but it’s not fully released yet. It has been fully spec’d out, and, of course, all of Web API, like ASP.NET, is open sourced, so you can get nightly builds that this actually works in. I decided not to use that because I wanted to make sure everything we were building and we were working with was going to be nice, stable code. Authentication vs. Authorization

Now that we’ve talked about some basic security semantics, being able to support cross origin sharing, requiring HTTPS so our communication, front to back, are nice and secure, let’s talk about the sort of meat of the story, and that is doing authentication and authorization. The difference between these two is important, so I want to make sure everyone that’s watching this really understands. Authentication simply means using a set of credentials to determine who someone is, what an identity is. So, in the case of typical users, that could be simply a username and password. It could be credentials like a client certificate. It could be a set of credentials that prove where a call is coming from, so a server to server can also do authentication without having to mimic sort of a single user. Authentication isn’t going to tell you what you’re allowed to do. It’s going to be the process of determining who you are, and that is used normally in authorization, and this is where it’s going to take the identity that you’ve created in the credentials in determining whether you have a right to a specific resource. So, this user that I’ve identified with authentication, do they have rights to this particular API or this part of a website? With that in mind, we want to think about what do we really want to authenticate? So, in some cases, we’re going to be allowing developers to use our API in order to do things like build mobile Apps, or build Tablet Apps, and so we need to authenticate who the developers are, typically done with an AppKey and a Secret, and the Secret is used for them to do encryption, and us to do encryption, and us to be able to compare the two. There’re other cases where you’re going to need to authenticate actual users of your system to determine who they are so that you can grant access to an API for those particular users. And, it may be as simple as, is this a user, or a super user, or a manager, or someone that has some particular set of roles, but sometimes you’re going to have your API only be able to return data that is associated with that specific user. That’s a very common case. This becomes important when you want to allow them to access the user specific data. Facebook is a good example of this. Once you authenticate as a user into a system, whenever you look at photos, and friends’ lists, and those sorts of things, you don’t have to give them your user ID again because the authentication that’s happened is telling them the context of what data you’re allowed to see. In these cases, it’s typically done with Basic Authentication, OAuth, or some sort of Integrated Authentication, like Forms Authentication in ASP.NET. So we’re going to be walking through each of these scenarios to kind of talk about where you’re going to do, and how you’re going to implement each of these kinds of authentication and authorization schemes. Piggybacking on ASP.NET Authentication

So, the simplest approach for Web API, since it’s normally written in conjunction with ASP.NET MVC, or ASP.NET WebForms, is to simply piggyback on ASP.NET authentication. Let’s see how that works. If we run our application, the default application is going to include the ability to Register or Login, so there’s a security system built in for users to use the actual website, and that’s what we are talking about the ASP.NET authentication. It may be as simple as we want to allow the API to work if the user is authenticated. If you’re simply using an API for your own website, this is probably good enough, because you can see if they’re not authorized, this simply forwards them to the Login page to force them to log into the system. So, without being logged in, I can simply go to the APIs we’ve defined, because we really haven’t secured them in any way. So, if I go look at, let’s say, diaries, I can see the diary, and this is the diary that we’ve kind of hardcoded to be my diary for this particular day. But if we go over here to the controller, and let’s go to the DiariesController, I can add a built-in attribute called Authorize, and this is to say that this diary requires authorization, and authorization implies that it also requires authentication. Let’s build it. And now that I have authorized, it’s going to fail, because it says this has been denied. Why has this been denied? It’s been denied because I’m not logged in. If we look at this in Fiddler, we can see that it’s returning as a 401 or an unauthorized exception. That message we’re seeing in the browser happens to be the message that we’re sending back to the browser to show us, but more importantly, we’re getting this 401 unauthorized. Because we’re piggybacking on it, and now that we’re setting it as authorization, we could go ahead and Login with a known user, like me. You can see now that I’m logged in, it has a Log off button and a Hello Shawn, so I can go ahead and look at my account. But if I had pages that needed it, I could now go to user diaries, because I’m authenticated by ASP.NET already. So, one approach here that’s pretty common is to support the Forms Authentication in ASP.NET, and then inside your JavaScript code, simply look for 401s, and if you get a 401, ford over to the known Login page. This isn’t always appropriate, because we’re going to want to support user authentication from other places, like Apps and devices, where they’re not always going to be sitting on our website. And, in that case, this doesn’t work at all. You’re not going to want to have them send these credentials into some API call that gives them a cookie that they try to insert into the browser for them, and it gets really kind of weird and sticky, especially for non-Microsoft clients that aren’t used to way Forms Authentication works. So, we’re going to explore some of those ways in a minute. But, one of the interesting things here is in looking at something like the API for diaries, we’re looking at a specific user’s diary. And we had hardcoded my name, but if we go back to Visual Studio, and let’s open up our Security class, Services, Identity Service, we were simply returning this hardcoded name. Instead, we can simply go to Thread, which is in System.Threading and look at CurrentPrincipal and the Identity of the CurrentPrincipal. This is going to look at who the current person logged in is, if any, and Name. The Thread.CurrentPrincipal.Identity are all going to be valid even if someone isn’t logged in, but in this case, the name will include the username of who is logged in. And, in fact, if we Refresh this, it will actually show us this because Shawn Wildermuth is the username I logged in with, and that happens to be the key in the sample data we’re using. But let’s go back and Log off and Register. Actually, I think it just needs a Login, I’ve created this account already, swildermuth. A whole different user, and so we can see we’re now logged in as swildermuth, and if we go to that same API, it’s going to be an empty array. Now why is this? This is because the database doesn’t have any record of swildermuth as a user. And, so when it looks for diaries under swildermuth, it’s getting it from this Thread.CurrentPrincipal.Identity.Name, it’s getting the name swildermuth, that, if you remember, let’s go back to the DiariesController, when we’re doing a Get here, we’re using the username from this IdentityService that were being injected in order to get the diaries for that user. This is why we implemented the IdentityService earlier so that we could use it as whomever the identity is for logged in user. Regardless of which sort of authentication or authorization we were using, this Identity inside the current thread will always work. Implementing Basic Authentication

Next, we want to get into building Basic Authentication. The idea behind basic authentication is that sometimes we can’t have our users Login to our website in order to authenticate through our normal web interface. This could be that you’re building an App to go against the API, or some other mechanic. So, Basic Authentication allows us to take the credentials of the user and pass them in through a header. That header will contain the information about the user, and then we can look at those credentials and decide whether that API call should be allowed or not. Unlike ASP.NET Forms Authentication, Basic Authentication is including those credentials on each and every call. So, in order to do this, let’s clean up our workspace here for a moment. And let’s go down to the Filters. So, now we’re going to create a new class inside the Filter folder. And, this new class is going to represent an authorization Filter. We did this earlier when we did the RequireHttpsAttribute, and we’re going to do the same thing here. We’re going to override the Unauthorized method, and then handle our Basic Authentication inside of that. We’re also later going to add Token-based Authentication to the same file. Because of that, I’m going to call it our own authorized attribute. So, CountingKsAuthorizeAttribute. Now this class is an AuthorizationFilterAttribute. So, it’s something we can apply either on everything, which is what we’ll actually do, or simply add it on the APIs that require user level authentication, like our diaries. I’m going to bring in the authorization filter attribute that’s in System.Web.Http.Filters. Now that we have the Filter, let’s go ahead and override our OnAuthorization method. This method is going to be called during the pipeline of making our Web API request. And this works simply by saying, if this OnAuthorization call gets made and the response of the call is still empty, or null, then it knows it can continue down the pipeline. We want to include information in the response with a failure code, and Unauthorized HTTP status if the authorization fails. So, let’s do this a little backwards. Let’s go ahead and handle the unauthorized first. So, that if any of the code we’re using doesn’t go ahead and short cut us out of this method, that the last thing that we’ll do in all cases is return an unauthorized response. So, I’m just going to write a method called HandleUnauthorized, and I’m going to pass into it this actionContext. This actionContext contains information about the request, but is also where the response is when you want to set a new response. Let’s go ahead and generate the stub for that. (Typing) So to handle it as an unauthorized request, we’re simply going to say the actionContext.Response. So, we’re setting the response to be a new actionContext.Request.CreateResponse. This might look familiar, because it’s actually the same method we use in our controllers. (Typing) Let me bring in the HttpsStatusCode, System.NET (Typing) and Unauthorized. So, we’re going to create a new response and set it to the response so that it shortcuts that action. Now, for our CreateResponse to work, we actually need a using up here to the namespace that contains the extension method. This namespace is System.Net.Http. Now, this might be good enough for handling unauthorized, but this spec actually tells us we should do one other thing, and that is help tell the user of this API how to actually authenticate. To do this, we’re going to actually go and set a new Header to be added to the response. This Header is WWW-Authenticate Header. So, in the case of the caller being someone how knows how to handle this, we’re going to try to give them some information about how authentication can be accomplished. We’re going to tell them with just a string value. The string value is going to tell them the kind of authentication we support, which in our case, is Basic. We’re going to tell them what the scheme is, and the idea behind the Scheme is telling it in what context these credentials are useful. Usually this revolves around a set of services that you’re exposing. This might be the name of your domain, it might be the group of services you provide. In our case, this is going to be a string called, you guessed it, CountingKs. And then finally, we can include a location. The location is simply an URL that points to where the user can do this authentication. In our case we’ll just go ahead and give them a URL over to our account login page. Now, you would probably want to compute what the actual web address here is, creating an URL, maybe creating an URL based on the Request URI. But, to get us through this quickly, I’m just going to go ahead and include a hardcoded location there. Now, not every client is going to know what to do with this. In fact, many of the browsers don’t know what to do it either. But, it will be useful for any client, especially developers who are using your API that may be aware of the WWW-Authenticate Header, and when they notice it, they’ll be able to redirect the user to the correct page. Because, we’re replacing the response in this case, we’re handling the unauthorized correctly. So, if we don’t end up running any of the code in here that shortcuts us out of authorization, we’ll make sure that every other call is going to be unauthorized. So how do we actually perform the Basic Authentication? We do this by looking at a specific header that’s included in the request, Request.Headers.Authorization. This header is going to contain information, if it’s been included, about how to do the authentication. So, we’re just going to go ahead and check to see whether the authHeader was included by making sure that it wasn’t null. Again, if it is null, we’ll fall down into HandleUnauthorized, and we’ll tell them some information about how to actually authenticate with the system. Next, we’ll want to make sure that the type of authentication header is what we need, and that is what it’s called a Basic Authentication Header. So, we can just check to see that the authHeader.Scheme.Equals basic, and we’ll just tell it to compare it without the worry about the Case. But we’re also going to make sure that not only has it set the authorization header to Basic, but that it includes the parameter, and the parameter is where the credentials are actually going to come in. So, we have to say authHeader.Parameter does not equal null. Or, more importantly, because they could pass in an empty string, we’ll go ahead and say it does not equal string is null or empty or whitespace. So if we get down this far, we have a valid authentication header. So, we’re going to want to pull out of that header the parameter. So we can get the rawCredentials from the authHeader.Parameter. That’s just going to be a raw string of the credential. Now, the parameter is actually going to be a Base64 encoded string, so we have to get it un-Base64 encoded. So we’ll go ahead and create a credentials equals Convert.From 64 Base String and pass it in that rawCredentials. So, this is still encoded, so we want to use the encoding to correctly get the username and password out of this Base64String. And this is important because the types of characters that can be included in a password might be symbols and such, and, of course, usernames could contain foreign letters, so we can’t assume this is just going to be something like ASCII. So, let’s get the encoding, and we’re going to assume in our case that the encoding is going to be, as the spec says, an iso-8859-1 encoding. Once we have the encoding, we can then say GetString for the data that is being returned from the Base64String. Now this always returns a byte array, and so the encoding allows us to decode it, and so these credentials are actually the raw credentials now. Now the credentials come in in a form of username colon password. Because of this pattern, we can go ahead and just use string.Split. So we can just take our credentials and call split, and we’ll just split it by the colon. And this is going to give us an array of strings both before and after the colon. This also assumes that colon isn’t a valid character inside the password. If it is a valid character inside the password, things get a little tricky, and you’ll have to make sure that the split is the first character. Certainly, a colon shouldn’t be a valid character in the username in any case. We’re going to assume in this simple example that we’re only to get two pieces of the credential, so we can say username equals split 0 and password equals split 1. So, one of the things you may notice here is that we’re getting actually a raw username and password in the header of a call, so this better be HTTPS. And, we covered how to force that for your Web API calls, but this is really showing that we’re not doing any sort of real encryption here. We’ll really getting the raw username and password. We’re going to talk a little bit about some other ways of doing that later, especially with OAuth, but Basic Authentication, which certainly works, does have the problem of being clear text and, as long as you’re using SSL, you can certainly protect it from the man-in-the-middle attack. You’re still going to have that the devices are going to have that access, so if someone else is writing against your API, they’re going to be directly collecting those username and passwords, and they can certainly see them. It isn’t getting around that particular problem. Now that we have the username and password, we want to be able the validate it. Now, we’re using the built-in ASP.NET Forms Authentication, so we can actually just thunk down into their code. They’re actually using a project type called Web Security that come with newer versions of ASP.NET. So, we’re just going to want to use that. We can say, if WebSecurity, and I’m going to include it, and this is in the WebMatrix.WebData namespace, and that’s because this was originally built for Web Matrix and is now being used with ASP.NET MVC, and I’m just going to call Login. Now, this code that we’re using here to do the credential check could be your code. If you aren’t using this built-in security, and you have your database with your own username and passwords, and you’ve built your own system for doing this authentication, just replace this code here. What we’re looking at for the Basic Authentication is really the same. We’re taking it out of the header, and then we’re using some code to validate those credentials. That validation may be very different depending on the infrastructure of your website. The Login takes the username, password, and we could pass in a third parameter to persist a cookie, but that actually doesn’t matter in our particular case. We’re going to leave it as False, which is the default. And, even though we’re talking about logging in, this is really just going to return a Boolean to tell us whether the credentials are correct. And, in this case, we can just say return. Because we’ve gone down this whole path of looking at these credentials, we’re saying return to shortcut it from handling unauthorized down here, doing all this work to make sure that the call to the Web API is able to be used. But we also need to be do one other little piece here, and that is we need to be able to set the identity to this new user. And this is an important part of the picture, because, if you remember, our security service is assuming that the Thread.CurrentPrincipal.Identity is going to be the correct name. This is something that Forms Authentication does for you, but because you’re doing your own authentication here for Basic Authentication, you’re going to have to do this. So, let’s create a principal. We can just create it by creating a new GenericPrincipal. And this is going to be in the System.Security.Principal namespace. And the Principal takes an Identity and then an Array of roles. So, in this case, we’re actually going to create a new GenericIdentity. So Identity is simply going to take the username that we’ve now validated, and then I’m not going to really give it any roles, that’s something you could add later so that you could test against specific roles as well. Now, that we have the Principal, we can simply say Thread, which is in System.Threading, CurrentPrincipal equals the new principal. And this is what forces that identity information to be included in the Thread that is about to process your Web API call, and therefore our IdentityService will pick this up. This has to be put into the Thread so then everyone down the line that’s using it will know who the current user is. Another approach here that we’re not going to show is you can develop your own principal and your own identity to include additional information. If you have the idea of roles, or other sorts of information around this identity that are important to you, you can certainly build your own principal and identity objects. And if we build it, and hopefully we got everything right. We didn’t, as our split actually takes chars not strings, so let’s change this to a char, and in theory we now have Basic Authentication working. So, two more things we need to do now that we have it building, is we have to talk about first this WebSecurity. If you are going to use the built-in security, before we can use it, we actually have to initialize it. On the face of it, it feels pretty easy because we can just say, WebSecurity.Initialized. If it’s not initialized, then we actually have to call WebSecurity.InitializeDatabaseConnection with a number of pieces, the connection string we’re using, etc. This initialization is actually happening inside of an attribute that is being used in other parts of the system. This InitializeSimpleMembership attribute is something that is part of the ASP.NET MVC4 template that we used. If we can down here, we’ll actually see that there’s a call to this InitializeDatabaseConnection, and we’re going to Copy their implementation of it. But we do have a problem. The code that’s being generated here actually is missing a little piece, as far as I’m concerned at least. And that is that it needs to do that same check we do. The code itself inside WebSecurity doesn’t know that if it tries to be initialized a second time, not to just throw an error. And because their attribute isn’t testing for isInitialized, we’re going to need to add it here, because our attribute may be called before their attribute. So, we just want to make sure that whoever gets in first, initializes this correctly. You can see what they’re doing is they’re using the DefaultConnection, and the configuration string, and then UserProfile is the name of the database in the data, and so we could certainly centralize this to fix this. And then their specifying the name of the UserName and the UserId, and telling it to go ahead and create the tables if necessary. So, nice and simple to initialize before we use it. Before we can really test it, we’re going to need to actually use the attribute. So, let’s head over to our DiariesController, and if you remember, we had been using the Authorize attribute, which makes sure that somebody in the pipeline has authorized it. What’s interesting here is this will take care of the authorization if it is forms-based authentication, but because we want to support Basic, we have to use our Authorization attribute here instead. By putting it here instead of the original authorize, it’s going to call us to make sure that their authorization is supported. This means we’re taking over the responsibility for making sure that Forms Authentication alone is going to be good enough for authorization. So, what we can do here is also just say if Thread.CurrentPrincipal.Identity.IsAuthenticated just return, just shortcut it. So if someone’s already gotten here and given us an authenticated user, we don’t need to check the Basic Authentication Header. We’re going to allow someone else, like Forms Authentication to handle this for us. If they haven’t handled it, then we’ll drop in and handle the authorization through Basic Authentication. So, let’s take a look what this looks like in Fiddler. Testing Basic Authentication

So, in Fiddler, if we attempt to make the request to diaries, remember we changed it to CountingKsAuthorization, it’s going to unsurprisingly give us an Unauthorized. Our code is actually being run, and we know that because we can see that the WWW-Authenticate Header is being passed in. We’ll telling anyone who cares that we support Basic Authentication, our Scheme name is CountingKs, and that the location, if you want to just go into a web browser, is to go to our account login. So, how do we actually authenticate here using Basic Authentication? We can do this by including the Header Authorization, and using the word Basic, so that we’re telling it we want Basic Authentication. This should look familiar, because we’re actually looking to see whether Basic is this type of the Authorization Header. Now, Header is just another line in the request. It’s nothing magical. It’s not a piece of XML or some additional file that’s being transferred. It’s just a piece of text that we’re including. And after Basic, we want to be able to give it the credentials as some just string after it. That’s the parameter of the Authorization Header. How do we actually encode this, because remember, if you remember from the code a moment ago, this was Base64 encoded, and encoded using a specific text in coding to support extended characters. There are ways to do this in JavaScript, but instead of diving down into client code, let’s just go ahead and make our quick version of it by using Firefox. So, let’s go to a website called base64encode.org. Simple little tool that I like to use for testing, where you simply type in some text, tell it to encode, and it will Base64 encode it for you. We’re going to actually encode our username and password separated by a colon. So, it’s going to be shawnwildermuth and my password is Pluralsight. Again, not the safest password, but you understand which. And, we want to make sure and encode it using what we’ve specified is going to be the right encoding, which in most cases is going to be ISO-8859-1. Let’s go ahead and ENCODE that, and here is that magic string we need to include as the parameter. There’s the parameter. In this case, we’re going to include it, and this is the Base64 encoded version of shawnwildermuth:Pluralsight, and if everything went well, we’re now getting our data, because we’re including our authentication credentials here directly inside of the Authorization Header. This means you’re going to have to have your client code, or you’re going to have to instruct the users of your API to use Basic Authentication in this way, as one of the ways they can actually do this. Now, again, if you don’t want to leak these credentials to the clients that are actually writing it, that gets a little more difficult in that we’ll need to use one of the other authentication schemes that we’re going to talk about soon. Before simple direct ways of just using headers to authenticate your application, this ends up being pretty easy. Tokens Authentication

So, in simple Token Authentication, the process works like this. The developer is going to come to you and request an API Key. This may be an application process. This may be just filling out a form on the website, and you automatically give them an API until they start abusing the service. But, there’s going to be some process, and they need to get a magic string that you’re going to use to identify who they are. By making this request, you’re going to supply them with an API that’s that magic string, and then some shared secret that you both can use to do encryption. The idea here is that you’re going to be able to have them encrypt something special on their side, pass in the result of the encryption, and then you, having that same shared secret on the server, can encrypt the same piece of information, and validate that they know about the secret. This process of requesting an API Key and getting a shared secret is a one-time thing. This does not have to happen every time a user uses your API. This is only going to happen when they register as a developer for your API. The developer is then going to make an API call to actually request a Token, and this request will contain some information that you can use to validate who they are. This request is then going to be confirmed that, yes, this is a valid user, we haven’t blocked them. The credentials they’ve given are correct. Therefore, they know the shared secret, is essentially what you’re doing. And, you’re going to return to them a Token. Now, this Token is another magic string that you’re going to be able to just put together and validate that they’re going to use to call your API. This Token is going to be tied to a timeout. This Token may be good for seven days, seven hours, seven minutes, depending on the volatility of the data, and how long you want to leave a window open for attack. Some APIs make this work for two hours, some of them make it work for a full day, but anything longer than that can really open you up to problems. This Token is either supplied in a Header, or just as a query string parameter, depending on how you’re working with it. If you’re developing a richer API, you’re probably going to want to support both mechanisms. The query string ends up being easier for the first time developer of an API. But it’s usually a little cleaner to go ahead and put it in the Header later. If you look at the way that Facebook, or GitHub, and some of those other APIs work, they usually support it in both ways. We’re going to just do it in the query string to simplify our naive implementation of Token Authentication so you can see it work. So, let’s start by implementing the token controller and request, so we can see how we want to store these things, and keep them around. If we come back over to Visual Studio, we’re going to start by actually creating a new controller, and I’m going to call it TokenController. In our case, the data access layer, the repository, already supports the idea of storing AuthTokens, as well as having API users, and so we’re going to base our interaction with data that’s already in the database. So, we’re going to, like all other controllers, change the base class to base API, and then just generate a new constructor that takes our repository. So, that our other parts of our API can actually have access to them. Next, we need the call that’s going to return back a Token if the information is correct, and the best way I think to do that is with a Post. We’re actually creating a new Token in this case, so Post is the correct verb. So, let’s go ahead and create a public method for Post, and let’s go ahead and return a ResponseMessage, because we want to be able to return rich information, like Unauthorized, BadRequest, those sorts of things. And our Post is going to take as the body of a message a JSON object that contains the credential information. So, in this case, I’m going to use that FromBody, as we’ve seen a number of times already, and I’m going to create a new class called a TokenRequestModel that includes that information we need that forms that request, and I’ll just call that model. And I’ll just use refactoring and let’s generate a quick version of this inside of the Models folder. Now, that we have that model, we’re going to want to pull some information out of it. So, let’s go over to the TokenRequestModel and just add two properties that we’re going to need. We’re going to need a string that represents the ApiKey. This is that magic key that they were granted when they registered with you as a developer, and we’re also going to ask them for a signature. This is going to be a string that’s going to contain information to verify who they are. This typically is going to be something that’s going to be encrypted on their side, and then like encrypted on our side, and compared to make sure that we both have the same shared secret for encryption. We’re going to implement this in a fairly naive way back here in the TokenController. First thing we’re going to want to do is get who is the actual API user. So, let’s get the user out. When I say user, I mean developer. I’m going to go to TheRepository in our case, and we’re going to GetApiUsers, and just look for our specific user. Our AppId equals model.ApiKey. We’re going to attempt to find the first user that has the ApiKey that was passed in. If user doesn’t equal null, we’re going to continue down here. And let’s go ahead and do the typical, let’s capture this all in a try, catch, (Typing) and we’re just going to return Request.CreateErrorResponse BadRequest, and we’ll go ahead and pass them in the exception in our case. So, if they get through the whole process without an Exception, we’ll go ahead and do the same thing, Request.CreateResponse, but just say BadRequest as well, but we’re not going to include the error information because we don’t have any in that particular case. Now that we have that user, we can actually get out our secret, right? We can look at this secret, and be able to figure out whether the signature we were handed matches the information that we’re using from our secret. For brevity, let’s talk about confirming that secret. I’m just going to Paste in some code and let’s talk about what it’s doing. In this case, I’m going to take the secret and I’m going to get the raw version of the secret. In this case, I’m going to convert it back from a Base64 encoded string, and then I’m just going to use SHA256 as my cryptography piece. And, I want to compute a hash, just simply based on using the secret that both sides have, and I’m just going to create a hash based on the AppId or the AppKey that is being passed in. Basically, what we’re doing here, and this is a very naive implementation, you’re going to do to something more sophisticated, is we’re asking the user of the API to encrypt the AppId with the secret we gave them, and we’re going to agree beforehand, and that’ll be in SHA256 encryption. And, we’re going to get a hash, and then we’re just going to compute a signature on our side of what is a Base64 version of that hash. Then we can just simply say, if signature equals the model.Signature. So, we’re going to say, did we both get the same result? We’ve agreed ahead of time to encrypt this string in same way, so we’re going to compare what they gave us to what we just computed, to see whether they are a valid actual user. If they are, then we’re just going to generate a brand new Token. So, the first thing we’re going to do is build up a string that contains the different pieces of the Token. In this case, we’re just going to concatenate the AppId from the user, as well as with the current date in UTC form. This will just be a raw string that we’re going to use to generate a unique string for our Token. Next, we need the bytes of that Token, and we’ll just get that by saying UTF8.GetBytes, and we’ll pass it in our raw Token information. We’re getting a version of the byte for the string because we need to send it through our cryptography provider in order to produce an encrypted version of it. Otherwise, people could very simply just craft these. So, our Token ends up being provider.ComputeHash, and passing in that raw array of bytes. Once we have this Token, we can go ahead and build our authToken. This is the object that we’re going to store in the database, so new AuthToken, and the Token itself could just be this Token, but, of course, this is expecting a string, and this Token is an array of bytes. So, we’re just going to want to convert this into a web friendly string, which we can do with Convert.ToBase64String. And, for our Expiration, we’re just going to compute something that is going to give this object a lifetime. In our case, we’ll just compute something seven days from today, so we’ll say DateTime.UtcNow.AddDays, and that way our Token will be good for seven days. You may decide that that’s too many or too few, depending on your use case. You may decide to make this is a 30-minute Token, or you might want to make it a 2-week Token. It really depends on the sensitivity of your data. And finally, we’re going to need to set the ApiUser. This is the user itself that owns this Token. Once we have this, we can use TheRepository to Insert our new Token, and we’ll just want to make sure that this actually saves. So, if Insert and TheRepository.SaveAll, both of those are successful, then we can actually return from this our new Token. Now that it has successfully saved, we’re going to want to return a Response. This Response is going to be Created, because it is a Post. Like all the other Post calls we’ve done earlier, we’re going to use Created as the return type, or a 201, and now we’re going to want to pass back in the authToken. But, of course, we don’t actually want to pass in this entire authToken because it contains information we don’t want to necessarily expose the user to. We really just need to give them two pieces of information, the Expiration so they know how long it’s alive, as well as the actual Token. We can do that by using TheModelFactory.Create for authToken. Let’s go ahead and use refactoring to generate that new method, and then let’s walk over to it and actually implement it. We’re going to make this public, of course, and what we’re going to return from it is going to be an AuthTokenModel. Now we don’t have this class yet, so we’re going to want to create it, so I’m going use refactoring and just say, Create a new type, and I’m going to create this new type in our Models folder, and of course call it AuthTokenModel, and let’s head over there and just implement this class. We’re going to want a string that represents the Token, and a DateTime that represents the Expiration. That’s all we’re going to return back to the user, and then, of course, here in TheModelFactory, this becomes fairly simple, we’re just going to say return new AuthTokenModel, and map those back, Token = authToken.Token. So, if we go back over to the TokenController now, let’s go ahead and Build it to make sure we haven’t done anything wrong, and it’s building. That leaves us with one last step, and that is adding the route. So, let’s head over to our WebApiConfig, and let’s create a new route for the Token. I’m just going to Copy this. I’ll call this our Token, and all we’re really going to have here, because the only thing we’re supporting is Post, is Token. Build it to make sure it works. And, now we’re ready to actually test it. So, we head over to Fiddler. So we go ahead and test this. We should be able to call Token, and let’s Execute it with nothing in it, and we get method not allowed because we haven’t implemented POST. So let’s go ahead and look at POST. Let’s get rid of that Authorization Header because we’re not actually using it for this. And we’re going to want to put together a request body that contains, if you remember, the ApiKey. Let’s make sure it’s valid JSON by quoting all of the names, and we’re going to also want the signature. A little Martha Stewart action to show you this. So this ApiKey was actually generated and stored when we seeded the database. So, this assumes that we’ve already registered and were given a magic string for our ApiKey, and then I produce this signature by doing the same thing we did in code a minute ago externally, so that you can imagine whoever calls this is going to have to do exactly this, give us the ApiKey and give us that signature, and hopefully if we Execute it, the result of this is going to be a Token we can use. Now, what’s interesting here, that being important to understand, is that we just requested another Token. The proper thing probably when we requested a Token is to go look for all the old Tokens and eliminate them, so this ApiKey is only responsible for a single Token at a time. And, the rules for that really depend on what you want it to be. It may be that you’re going to allow 5 or 10 Tokens at a time, or it may be that you only allow 1, so the cleanup of those old expired Tokens is really going to be up to you. Now that we have a way of generating the Tokens, let’s talk about actually handling the Token-based Authorization in our Filter. Implementing Token Authentication

So, we’re back in Visual Studio so we can implement the Token Authentication. We’re going to start out by creating a constructor for our attribute, because we want to be able to store some data that can be passed in when we’re using the attribute. In this case, we want to pass in a Boolean that says, should we authenticate per user, in other words, use our Basic Authentication, or just allow people to use the API if they just have the Token-based Authentication. Typically both of these are going to get married together. The Token Authentication is going to be used to figure out who the developer is, and whether they have access to the API, and then Basic Authentication in order to determine the user of the API, so that we can do things like return the right diaries for that particular user. We’ll go ahead and just store this as a local field. So, in our authorization, there’s going to be two steps really. There’s going to be authorize it using Token Authentication, because we’re going to require anyone with this attribute to use Token-based Authentication, and then once the Token Authentication has completed, we’ll go ahead and allow the perUser Authentication. So, to do this, let’s go ahead and wrap all of our existing authentication that is user-based inside an if perUser. So that this will only be valid and checked if perUser is true. So, let’s talk about what that looks like. Let’s make sure that perUser is true by default. So, we’re going to give it a default value. That way when we look at where we included it, like in the diaries, it will be perUser by default. But this is going to allow us to go back to something like the FoodsController and add CountingKsAuthorize with false as a parameter to say, hey, we don’t need to do user-based authentication here, but we do need to authorize it for the API users. Not for the actual users of our system, but that the developers that are using our APIs must have an API Key, and have gotten a Token and using it. Hope that makes sense. So back in the Authorize attribute, we have this little piece where it’s checking to see if it’s perUser, and if it’s not perUser, we can go ahead and shortcut out of here. And we can shortcut out of here because if we’ve already gotten to this point, we’ve done the Token-based Authorization, we’re about to add this outside of this if perUser. So how do we this? So what we’re going to expect is that when a user calls our API, let’s say nutritionfoods, that we’re going to expect that they’re going to pass in a parameter for their API Key and Token. So the API Key is just the same key that we gave the developer when we originally registered the developer, and we’ll just pass that in on the query string to make that easy. And the Token will be that Token that was passed back here. We go to Raw and let’s grab that Token, and let’s go ahead and change this to a GET, get rid of the ContentType, and get rid of the Body, because now we’re just going to implement a GET, but we’re including the ApiKey and Token up here in our parameters. So that means back on our code we need to do a couple simple things. First, let’s create a couple of strings for the name of the parameters we’re looking for. And I’ll do another one for, because we’re going to need them in a couple of places. Next, we’re going to be want to be able to get the query string, and we use HttpUtility to do that. We can parse the query string from the actionContext.Request.RequestURi.query. And this is going to return to us a name value collection. So we can go ahead and test to see whether we have them passed in. If not string, empty, or whitespace, query, APIKEYNAME, and not string IsNullOrWhiteSpace, then we can actually process this. We have the query string. We can go ahead and put the end of this if way down here, and we’d probably refactor this into a couple of methods to make it not a giant method like we’re doing here, but let’s, because of our time constraints, let’s do it this way. Now, let’s go ahead and pull out the apikey and the token. So we want to go ahead and use that Token and Get the authToken. But in order to Get the authToken, we actually have to have an instance of TheRepository, just like our controllers do. So, if we go ahead and create a new property down here, and let’s add the using we need here, then we can use that repository to go ahead and get our Token. And we’re going to pass in the Token if the authToken doesn’t equal null, in other words, we found it, then we can verify that the authToken.ApiUser.AppId includes the same AppId that was passed in, apikey, and finally authToken.Expiration is greater than DateTime.UtcNow. As long as the expiration is greater than now, we’re going to allow it. In fact, this is all we need to do. We’ve gotten the Token and the ApiKey from the query string and, once we’re happy with it, we can pass it down to do our perUser Authentication if necessary. Now, we could go ahead and test this, and we’re going to find immediately that TheRepository is going to be null, because we’ve provided a place for TheRepository, but we didn’t provide a way to get TheRepository in there. So, we’d like to be able to use the dependency injection we were using earlier. And we can actually, but figuring out exactly how the filters are going to get this dependency injection is going to require a new class. So to prepare for it, let’s go ahead and use an attribute called Inject. This is going to support something called property injection. Because construction can’t be controlled by Ninject, because with the construction as part of the attribute, we need to have a way to take the object that is the attribute, and tell Ninject to go ahead and find all the properties with the attribute of Inject, and try to fulfill those services. In this case, supply it with a repository, and this should happen before authorization happens so that when we get down here to look for our Token that TheRepository isn’t null. But, how does that happen? What this requires is that we build a new Service, and this new Service is going to be injected into the pipeline of what happens inside Web API so that when the Filters are provided for, we’re actually going to implement a Filter provider, we’ll be able to look at all of the attributes for a particular controller, look at their Filters, and then be able to supply dependency injection to those Filters for them. So, we’re going to create a new class called NinjectWebApiFilterProvider. This is a sort of class that probably will eventually be supplied by either by the framework of Web API, or be supplied by the WebApiContrib project. One doesn’t exist yet, and I may even submit this to them to include there, so you don’t have to actually write this over and over again. But for our example, I just want you to see how the pipeline actually is being used. So, I’m going to implement FilterProvider. This is an interface from System.Web.HttpFilters. This is a Web API version, and this is going to simply have a call that says Get the Filters for our system, and let me fix up some of the namespaces. So based on the configuration and the action description, how can we go ahead and get all the Filters that are going to be required. And the benefit of doing this is we’re just going to gather the existing Filters for the controllers, and then before we pass them back in there, we’re just going to use dependency injection to Push any required services into the Filters before we pass them into Web API to pass off and do the work it needs to do. So, I’m going to go ahead and just Paste some code so you can see what this is doing. We’re using the actionDescriptor to go ahead and get all the Filters that are for controllers. We’re also using the actionDescriptor the get all the Filters that are for actions. And then we’re building a list of them by just mixing the two. We’re concatenating the controllerFilters with the actionFilters to get a master set of Filters. From there, we can just do a quick foreach, and then do the Injection. This has us just return that filter collection. So, again, what we’re seeing is finding all the Filters, doing the dependency injection, and then passing back those filters. This is just a plugin so we can get into the middle of that operation. In order to do the Injection though we’re going to need the Ninject Kernel object. So, I’m going to create a constructor here that’s going to take the IKernel object that’s in Ninject, and just store it as a local field. That means for the Injection we can then just do kernel.Inject my providers in the filter.Instance. This the instance of the object that we’re going to Inject using dependency injection into whoever needs it, in our case, the property. Next, we need to register our FilterProvider with Web API. So, just like we supported Web API earlier by using NinjectResolver, we’re going to do a similar thing here by adding to the Services of the configuration a new FilterProvider. Bring in that namespace, and this is just going to be a new instance of our class, and because we have access to that kernel, we’re going to go ahead and include it in there, so that the FilterProvider we just wrote can use it to do the Injection. If we did this right, then when we come down here and get to pulling out the authToken, TheRepository shouldn’t be null, it should be fulfilling it with the same sort of request that we’re seeing when we build our controllers. So let’s see if we’ve done it right. Yep. So because the ApiKey and Token are on here, it’s authorized. I’ve taken them off and I’m getting a 401 from our project, and if I put them back on, we can see we’re getting a nice 200. And, if any part of this is wrong, let’s say I had an extra equals at the end, which is obviously going to make it broken, it’s going to bring back the Unauthorized. Now we could give them more information about what is authorized or what is not authorized, but that’s really up to us. So, ultimately what we’ve done is we’ve added the ability to pass back Tokens and then use this same Filter mechanism to be able to test those Tokens, and in the case of user-based calls, so let’s go back to our call for UserDiary, I’m going to drag it over to the Composer so we’re generating it again. If we Execute it like we did before, it’ll actually say Unauthorized, and the reason is we may have our user information here, but we do not have our ApiKey and our Token. Remember they’re working together in our authorization attribute, so now that we have both of them together, we’re getting the actual data. Because it has checked to make sure that the developer is valid, so it has authenticated the developer, as well as using the Basic Authentication Header to validate the user. The last piece of this puzzle that you should actually do now that we’ve added a separation between Token-based and perUser-based authentication, is down here in the handle Unauthorized. The inclusion of the WWW.Authenticate response header is only really valid when we’re doing perUser Authentication. Otherwise, pushing them to a Login page doesn’t make any sense. So, it’s usually pretty helpful to just go ahead and protect this with if perUser. The Unauthorized is still appropriate in both cases, but this Unauthorized will only apply to the developer being unauthorized in the case where we’re only using Token-based Authentication, where we’re not using perUser Authentication. When we are, we’re going to go ahead and include that header that we saw back in the Basic Authentication example. Walkthrough of OAuth Implementation

So, the last kind of security I’d like to talk about is OAuth. OAuth is a standard. There’s an OAuth and OAuth2 that’s going to allow a developer writing an application to be able to use your service without having to collect the credentials themselves. Basic Authentication works really well, except that it leaks the credentials to the developer that actually developed them. So, you can imagine if I was building an iPhone App and I wanted to interact with a REST-API, I could certainly do that, but if I need to be able to create that Basic Authentication Header, I’m going to need to ask the user to give me their username and password. Now, if I’m a good conscientious developer, I’m going to just pass those along, create the header, and be able to do the work I want to do. There is, in some way that the user needs to trust me as a developer because they were willing to put my App on the phone. But, to make it so that I don’t have to have any of those credentials ever, OAuth was really generated. And let’s talk about what that looks like. It’s similar to Token-based, but there’re some extra steps that become crucial in allowing this whole process to work. The developer, like before, requests an API Key, and then the service, you, would supply them with an API Key and a shared secret, just like before. And then the developer, when they’re ready to work with it, they’re going to ask you for a Request Token. This is a Token to allow you to ask for the user to be prompted to approve that your API can be used by this application. So it goes ahead and validates the information and returns the Token. And, again, this Token is much like standard Token-based development. But, this is only to allow them to call into the OAuth service itself. At that point, the Token is returned and gives the developer a URI to redirect the user to. In a phone application, they will redirect them to a new URL that the API developer actually owns. The API will display this new UI saying, Bob’s App wants you to give permission for Bob’s App to be able to access certain parts of the API. They want to be able to look at your diaries. They want to be able to get the summary of your daily consumption let’s say in our case. And once the user approves that, they can go, yeah, I asked for this. This is cool. The API goes, okay, the user said it’s okay. It sends a result back to the developer saying all this was cool, you can now actually request a Request Token via OAuth, so this allows them to get a Token, which they can then call the API, and this Token, unlike the one we just created, is embedded with the information about the user. So, that when this Token is used on subsequent calls, it now only knows who the developer is, but it also knows what user the developer is acting on the behest of. So that when that Token Authentication happens, it knows, okay, not only has Jake’s Software Shack successfully called our API, but that Jake’s Software Shack is acting as Bob on our website, so when he asks for diaries, we’re going to return Bob’s diaries. And that’s the core of what OAuth does. There’s a lot of moving parts here, and this is what has been confusing, but it’s actually not that hard to build. Because of time constraints, and the state of Web API today, building this by hand I could to an entire course. I could spend six hours building this in front of you. Instead of that, I’m going to punt a little. I’m going to talk about a nonrelease piece of code. Let’s take a look of an OAuth implementation using some code that is not in release form yet, and so I didn’t want to have our project depend on it. It doesn’t work well with today’s version of Web API, but it will work with Web API2 when it releases. So here in Visual Studio, we’re actually looking at the .NET Open Auth project. This is a project, it’s an open source project. You can see at the bottom of the screen a link over to it, and this includes implementations of OAuth1 and 2 that work with different parts of the .NET framework. In fact, this is the open source project that the ASP.NET MVC team is using to implement things like third party OAuth registration. When you see someone using ASP.NET MVC and allowing you to Login with your Google, your Facebook, or your Microsoft account, this is the project that’s allowing that to happen. One of the new features that they have is this ability to become the author of an OAuth implementation. Originally their primary focus was being the consumer of an OAuth Token, so that you could accept the credentials from a third party, like Google, or Facebook, or Microsoft, but now they’re supporting the ability to create your own server that’s going to pass out OAuth Tokens to allow people to call into your service at the behest of other people. So, there’s a few different pieces here. They have an example in it called the OAuth2ProtectedWebApi example, and I would suggest if you need to implement OAuth in your implementation, this is the best place to start. This is a fully featured Web API example, but it’s really depending on some new features of Web API. It is tied to prerelease versions of Web API, as of the recording of this course. When Web API2 ships, this will be able to be used full and foremost with that implementation. This is why I’m not implementing it with our walkthrough example is that it’s just not compatible with today’s version of Web API. So the trick here is that it has a few pieces that are important. There is a TokenController and the TokenController, much like the one we just built, has a simple Post method. They’re using asynchronous communications, which is not a bad idea, to handle a lot of these things asynchronously, but for our needs, I’m not going into it too deeply. But they’re using something they’ve built called the AuthorizationServer that knows how to handle these requests. When you build your own implementation, you’re going to be building parts of this AuthorizationServer that know how to store these secrets, and how to validate, and how to tie to individual users. That’s the work you’re going to do. When someone gets these Tokens that they’re being asked for, it’s going to redirect them to an individual page, and you would implement this in any technology you want, but they have an example here using Razor and ASP.NET MVC, and this simply just pops up a form that says, hey, is this what you really want to allow them to do. If you hit approval, then the controller that is called, this UserController, just processes a Post to that operation. It looks at this and just looks at the AuthorizationServer, looks at the information, and puts together a grant. It essentially just will automatically put together a response that includes a generated Token for them, and the redirection that is necessary. The last piece, much like what we’ve built before, so now you have a sense of how you would build these, is they are actually just creating something called a BearerTokenHandler. This is a handler much like what we did that when operations are done, they’re just looking for a special kind of header. You can see here they’re looking at the request.Headers.Authorization.Scheme to be Bearer, much like we did with Basic. If it’s Bearer, then they’re taking the information in that header and then using it to find the current user and to, surprise, surprise, set the CurrentPrincipal to be the CurrentPrincipal of the website. So, this is a great place to look. I’ve sort of hinted at some of the pieces here, but most of what you’ve learned before are key pieces to the way you would implement OAuth. The harder parts that .NET OpenAuth can help you with is actually building the server and the services that know how to do things with the Tokens, how to redirect to the authorization page. To implement the authorization page so that you can confirm that the user actually wants to be able to share this Token with a third party, and to Accept that Token that the third party’s using as a Bearer Authorization Header. So, let’s wrap up this module. Summary

So, at some point most APIs are going to need to be secured, unless you’re building this very open framework to do things, like getting the weather report, or stock prices, you’re going to want to secure your API. First and foremost, if you need to secure your API, you really should start by requiring HTTPS. It’s probably a good idea for your entire website, but certainly for your API, this becomes crucial when you’re trying to secure the API. Allowing other websites or applications to get at your API can be made easier by integrating JSONP and allow CORS so that you can more easily allow these other people to use your API. You can, in many cases, simply piggyback on top of ASP.NET Authentication to simplify this process. And, when you need to implement a Token-based Authentication scheme using your own Filter to do both, Token-based, as well as Basic Authentication, becomes pretty straightforward. On the more difficult part of the spectrum, using OAuth to allow this user-based authentication, as well as verifying whose using your API from a developer standpoint can be accomplished. There’s a lot of moving pieces, and using projects like .NET OpenAuth can certainly simplify for you that process, but it does require some work. This has been Module 3. I’m Shawn Wildermuth. Thanks for joining me.


version —

Using SDammann’s Solution

So we’ve looked to see how versioning actually works underneath the covers and how we would implement that ourselves, which is a pretty viable option. But some people would like to just lean on others to do versioning when they don’t want to spend a lot of time really digging deep into the details. And that’s where the SDammann project can help you. Let’s take a look at it. I’m not going to go into a deep example with it, but I do want to introduce you to it and show you where it is. So, in github/Sebazzz/SDammann.WebApi.Versioning, there’s a project out there that was generated to really allow an easy way for people to plugin versioning into their applications. The idea behind the library is really to either derive your own, or to use one of the built-in controller selectors that they are supplying. These selectors handle some default implementations. So, for the URI solution, he’s actually advocating the version here, that is going to be passed into a RouteVersionControllerSelector, and you would use that out of the box, and it would do what you really want to do. There’s also one for VersionHeader, one for AcceptHeader, and in most of these cases you’re going to have supply exactly the types that you’re looking for. He has some good walkthroughs of how this works, and there is also a NuGet package that will allow you to go ahead and add it to your project. The benefit here is that you can kind of drop in the solution and just go. The negative for me is that using this library is implying some standard set of versioning semantics, and to get over the way he wants you do to do things. The reason I might not use this in some cases is that he’s supplying some patterns for doing the versioning, and if you’re application fits into that well, that’s great. Let me give you an example of that. If it doesn’t fit into it, you end up doing a lot of the work that we’ve already shown you how to do, and you can see it’s not that much work. So, if we look at his library, his library’s assuming that each of the versions of your controllers are going to be in named namespaces. So, you’re going to have duplicate controllers with the same name. Now on the face of it, that’s kind of elegant, right? You’re using namespace to imply version, and that’s all good, but for me, working in Visual Studio every day like I do, having two classes up here, both with the same name, knowing which one I’m working in can end up being a bit of a headache, and there are solutions to that, but I find having the separate names actually works better for me. There is no good way without really digging into and writing your own selectors with his library for doing that. He is assuming that the versioning is really going to be resolved using a namespace. And if you’re comfortable with that, his library’s great. I would expect at some point in the future some of this to be built into the Web API code base as well, though right now it’s not planned for Web API 2, so I wouldn’t depend on it. You’re either going to be writing your own controller selectors, or using a third party library like this one. Let’s wrap up this module. Summary

So, we’ve talked a lot about versioning APIs in this module. And, hopefully you’ve seen that versioning can be difficult, but is a necessary part of having an API that users use. Version controllers can get you pretty far there in separating both implementations that have to exist, ones that you haven’t sunsetted, as well as new implementations that may have an expanded functionality for new users. The controller selector becomes key in most situations where you want to do versioning to figure out how to point at specific controllers in specific cases. You can certainly do Routing to do this all in the URL path, but I find that that ends up becoming more maintenance than it really helps. You’ve seen that you can version your API in a variety of ways, and the one that works best for your project is really going to be a domain decision. So, for organizations where your user-base may not be all that sophisticated, being able to do things, like using the URL or the query string for versioning, is a really simple approach. For having more sophisticated developers that are going to use the API using Headers, Accept Headers, custom media types, or even just a Version Header, can certainly lend itself to separating the idea of version from the URL, which tends to be cleaner in the long run, and helps maintenance of your API. Finding which one is right for your organization isn’t a trivial exercise, but as you look and play with how these things work, and hopefully follow it along as I wrote the code, you should start seeing the one that your organization is probably going to be most comfortable with. This has been Module 4. My name is Shawn Wildermuth of Wilder Minds. Thank you. REST Constraints Introduction


What are REST Constraints

The next constraint is the notion of a Stateless Server. This is layered on top of the Client-Server idea in that you do have that separation, but when requests are made, . So that if later the client makes another call, it must include all the required state to make that call. There are no notions of the server remembering how you are, or what you are; you’re going to need to include everything in your request to define the kind of operation you want. In the web space, this works pretty well, but you do have to remember that we Each request should be completely stateless so that when these requests are made it doesn’t matter what machine is serving them, and you don’t need to necessarily share state across these different machines, and so scalability is improved through this. And this is part of the requirements for REST, and this is why it is a constraint of REST. Through the code that we’ve been building, you should already see that everything we’ve been doing so far has been pretty stateless, so there’s nothing special you need to do in a Web API project to make this work. Unless you go outside the bounds of what we’ve been talking about, ASP.NET Web API typically ends up being stateless. Calls into the service to do Posts, or Gets, or Puts, all include the different data that is required. It’s going to include the data that needs to be changed, as well as context, like the user information we saw in the security module.

Uniform Interface

The next constraint we should concern ourselves with is the Uniform Interface constraint. If you remember, the uniform interface constraint is broken into several pieces. So, let’s talk about them individually. First of these is the identification of resources, and that means that each resource has a URI that points at that, and only that resource. In this example, we can see from our API that a food with a particular number points at an individual food, and will always point at that same food. Properties of that food may change over time, but the identification of an individual food won’t change. Same with user diary. We’re using one diary per day for that user, so this URI is going to point at just that individual diary. And the same for our diary entries. The next part of it is a manipulation of resources through representations. And the idea here is that the same structures that are received through Get, can also be used for Posts, Puts, Deletes, Patches, so that what you’re going to get is going to be enough data to go ahead and make changes, whether that’s a Delete, or a Put, or a Patch, later on, in the usefulness of the API. These same structures are going to be used over the standard HTTP verbs that represent the different kinds of operations. The next part is that the messages themselves are self-descriptive, and this includes some of the concepts around hypermedia as the engine of application state. What we mean by this is that the state of the object can be represented as links, and these links are going to give enough information that the user of the API should be able to discern what are the things that can be done with this representation of the entities on the server. So links become very important and a key element of what you’re going to be building if you’re going to support things, like hypermedia. So what do links really look like? Here’s an example result of a food. And in this case, we can see that part of the description of this food is going to be a set of links, and these links are going to tell the user of the API a way to use this object. In most cases, the one required link is going to be a self-link, one that has the relative value of self. And this is going to include a href to the URI that represents this object itself. This gives the user the capability of doing things like issuing this URI and the Delete in order to try to Delete this element in the API if they are entitled to that operation. Here we have a second link that represents getting the measures for a particular food, and we’ve included the URI for that. Even though the URI is fairly self-describing in telling it how to get the individual measures, and even though we’re actually including it here, telling them how to get the measures for this particular food, this entity returned from the server is becoming more self-describing. Now, I wouldn’t go overboard and implement links for every possible operation. That can get overwhelming, and unnecessary, but where it can be useful is when you want to help infer automated systems that are going to know how to do things, like moving an entity from one state to another. That’s where HATEOAS really comes into its own. You can imagine that if this were an invoice object, we might have different links here for moving the invoice from the pending status, to approved status, to shipped status, to paid status, and so moving between those states we could hint at the API ways to move it to the next state, or to move it into a problem state. These links become useful that the users of the API can look at those, and that also they’re not depending on particular URI patterns, that you’re always going to be supplying the URIs that represent that next state. So, let’s see how to implement this in our own code. Implementing Links

So, now let’s take a look and implement links in our example application. We head over to Visual Studio. We’re going to take a look at the Models folder, and before we can change our application to support links, we’re going to need a model for a link itself. So, I’m going to create a new Class, and I’m just going to call it a LinkModel. And let’s use some snippets to create our individual pieces. So, I’m going to have an Href, a Rel, and we saw both of these in the example. I’m also going to include two more, and one is going to be a Method. And that way we can hint if the operation is not a Get; if it’s a Post, a Put, a Delete, etc. And finally, I’m going to have a Boolean in here for IsTemplated. IsTemplated is an indicator of whether the Href has template elements. There’s a standard for using templates inside of an Href. We’re not going to really cover IsTemplated, but I’m going to show you what a link should typically look like. Now that we have a model for our link, let’s head over to DiaryModel, and let’s replace our URL here with a collection of link models, and let’s just call those Links. Here we’re going to continue to supply an URL that represents the item itself, but also gives us the ability to add additional links for other operations as necessary. And, we’re also going to need to go to into the ModelFactory and change our code to support that. So, if we look for the Create that is creating the Diary, we’ll see where we’re specifying the URL here for the diary. But, since that’s gone, let’s go ahead and change this to include our new Links. And, I’m just going to use a collection initializer to include a number of these Links. So we know that one of our links we want to be the same as we were specifying here for our URL. Let’s get rid of that URL. But the Links themselves aren’t just strings. Remember they’re these more complex structures, so let’s create a new method called CreateLink that’s going to take one or more parameters. For our first parameter, we’re going to always include the URL that is generated by the UrlHelper. For our second parameter, we’re going to include a string, and in this case it’s just going to be called self. So at a minimum we’re going to want to supply the Href part of the Link, and then the Rel part of the Link that we’re going to generate. So, let’s use refactoring and generate this stub for us. We’re going to want to have other people creating Links, so let’s go ahead and make this public. So this is going to be our href, and this will be rel, and all we’re going to do is return a new LinkModel, and we’re going to set Href = href, Rel = rel, but remember we also have the Method and the IsTemplated. So, let’s actually support those in CreateLink as well, but let’s not have to supply them. So let’s say, string method = GET and bool isTemplated = false. So for our use, we’re going to default back to a Get, and IsTemplated = false, so we can go ahead and say that the Method is going to be an isTemplated. So, we’re now creating that Link. Let’s make sure that we compile, and here we can see that we need to deal with the diary needing to parse that URL. So, in this case we’re just going to make a little change. We’re going to say, let’s call it selfLink and we’re going to say model.Links where rel equals self, FirstOrDefault. So, we’re going to go ahead and grab that selfLink if it exists. So, if the selfLink does not equal null, and the selfLink.Href is not empty, then we should be able to just specify the URI using that, and that way we can parse and get out that ID like we did before. Let’s see if we have any other places. And let’s go ahead and just make sure that we put that and in there that I’d missed. Let’s Build that. And, if we go back to the browser, and look at this diary, we can now see instead of that URL we’re getting a link that includes the entire piece of data we had expected. Here’s our method. Here’s our templated, rel, and href. So, in the usual case you’re going to be creating more than one Link. So, let’s create a couple more. Let’s create a newDiaryEntry, and, of course, the Method for new entry is going to be POST, but, of course, our link won’t be the same. We’re going to need to go after DiaryEntries as a Route, but we can just use this same Link for the diaryid. Now, if we Build this, and Refresh, we can see we have our new entry, it’s including the different information we’re supplying, and we’re saying, hey, when you want to Post a new diary entry, here is the href for this individual diary. It’s going to give them some information about what has to be done. It’s not being incredibly useful for saying what’s the structure of a new entry, any of that. That’s still going to need to be something you’re going to need to document and share with the users, but this will hint at them additional links. And it’s very common to have more than one link for each particular entity. Putting these links inside of the entity itself, and having it being self- describing is useful in our case because it may be that individual entities have different operations. So, being able to have these links go to individual states like we had talked about earlier, the example of this being an invoice, and one invoice may have an operation to say, send to fulfillment because it’s in that state, whereas the second invoice may have its own set of self-describing link that says, send to approval, because it’s in that state. So, the links that are included here may be very dynamic. It may not be the same links are going to be included for each and every version of an entity that was returned from your API. Let’s look at a different place where this can be useful. If we go back and look at our controllers, let’s go to that FoodsController, and if you remember, we we’re doing this trick where we were building up the link for the previous and next URL. And that’s interesting, but instead of including both of these, and remember, let’s actually show you in the browser, we’re including an empty string for the previous PageUrl because there isn’t a previous page, and then a nextPageUrl for what is the next page, and as we go to the state where we have a previous and next for filling them out. And that’s fine, but I hate including the empty one when we don’t really need it. And that’s where we could benefit from actually creating a collection of our LinkModel and then adding to it. So, we can just say, if page is greater than 0, links.Add, and in this case I’ll Add a new Link by calling TheModelFactory CreateLink. Remember we had made it public earlier. And we can keep what the helper is giving us, but then pass in what would be the rel, which would be nextPage, and we’ll leave it as a Get and nontemplated because that’s fine, and we’ll do the same thing we we’re doing here. If, and let’s borrow this little if, links.Add TheModelFactory CreateLink, and then at the end of this we’ll name this previous Page, and we’ll just do the same thing here. If, and let’s borrow this little if from our earlier implementation, links.Add TheModelFactory.CreateLink, same helper Link, except that here we’ll say nextPage. Now that we’ve added Links specifically for previous and next as necessary, we can replace what we’re returning here with just a new member called Links that will be serialized as a collection of these links. If we go to the Foods, we can see that we now have one, and only one link, because there is only a nextPage. And if we click on it, we’ll then get a previous Page and a nextPage based specifically on the links that are valid for this particular URI. And so we can use this concept of links both in a strongly typed sense with what we’re generating for our models, like our DiaryModels and our FoodModels, but we can use those same ideas to augment the results we’re getting like we did here in Foods. And I’ll propagate these changes to all the different objects before you get the source code, assuming you have a Pluralsight Plus subscription. I’m not going to waste your time here in the video repeating this process for each of the different entities and models in our system, but you can expect that that’s what you would want to do, replace all the URLs with links. Improving Link Serialization

So, let’s go back to our diary for a moment, and one of the issues here is that we’re showing elements in our links that might be unnecessary. Like, isTemplated equals false, we can assume it’s not templated, and may be not even show this property, and so we might want to make the decision when we’re generating these to only generate the ones we actually have to have. What I’d like to have happen is that the link is going to be an Href and a Rel, and assuming the method is GET, unless we say it’s not GET, like it is here in POST, and the same for isTemplated, show the property as templated only if the isTemplated equals true. So, the problem with this is that you might very easily think, oh, I’m going to have to drop down into anonymous objects or things like that in order to get that behavior. And, so this represents a good place where we can actually show you how serialization is separated from the implementation of the API in Web API. The way this works is if we look at the configuration, and because JavaScript is a loosely typed language, we can get away with doing this. We might not do this in our XML formatter because we need to maintain a consistency of DTE, that an object always is going to have certain elements. But, in our case, let’s go ahead and change this by saying jasonFormatter.SerializationSettings.Converters. Now, a converter is this idea of an object that knows how to convert certain types into and out of JSON. So, we’re going to actually add a new converter, called, surprise, surprise, LinkModelConverter, and we’re going to simply Add that to the collection of converters. Let’s create a new Directory for our converters, because we might have a handful of them. And let’s go ahead and create our new converter Class directly in that new folder. Now that we have that, let’s go ahead and fix up the namespace here, and just include it in our Config, so we don’t have to come back and deal with that later. So a LinkModelConverter can derive from a JsonConverter. This is a class that is exposed by Newtonsoft.Json, the JSON.NET project that’s used for all of our serialization, and it has three required methods, the JsonConverter class itself is abstract, so it has certain required methods that you have to fill out. So, let’s go ahead and just stub them out for us. And, the first thing we’re going to want to do is determine that the type that is being passed through the system is something that this converter can handle. And the way you do this is in the CanConvert, you return true or false based on looking at the type that’s being converted. So, in our case, we’re simply going to say, if objectType is equal to the type of LinkModel. Now, there are other ways of doing this. You could say, is equivalent to, or can be derived from. There are other ways of doing this, but for our case, we know that there’s only one, and one type of LinkModel. Later on we might want to create some different derivations of this, and do something different here, but for the simplest case, we’re just going to say this convertor can handle it if the type being converted is a LinkModel. Now, when JSON.NET reads JSON coming in, and wants to convert it to an object, we’re going to let it. We’re just going to say, reader.Value. So, we’re basically going to tell it, go ahead and use the default implementation, which is to read all the properties on the JSON object and apply them one-to-one to our LinkModel. Because we don’t really have an override, we want to deal with that. If there’s something different in the way we’re structuring it, we may need to actually implement this read JSON manually. But in our case, we don’t. For us, the real magic comes here, and that is where we want to write our own version of the JSON. We’re going to first get an instance of the object, the value, by saying value as LinkModel. We’re doing as so that we can then just make sure that we’re only doing something special here if the value being passed in actually is a LinkModel. This should always be true, but it’s just a sort of a sanity check I like to put in. You could also say, if value is not a LinkModel, then throw an Exception so that user knows that. It’s really up to you which path you want to go down. So, we’re going to start this by using the writer, and we’re going to say, WriteStartObject, because we’re telling it that we want to start an object in the JSON. It’s going to know that the writer is at the point where our link has to be injected into the JSON stream, and we’re going to say, we’re going to write an object. So, let’s start that object. We’re also going to end it with WriteEndObject as bookmarks to the actual implementation we want. So, let’s first write our first element, which is going to be WritePropertyName, and here we’re going to write a property name of href. We’re also going to Write the Value which is going to be our Model.Href. This is how a single Property and Value are written into the JSON object. Now, if we wanted to rename these in some way, we would then, in our read, have to do that conversion between the names as well, but they’re the same, so we can just deal with it in that way, and we’ll do the same here for rel. And this is where we’re actually doing some overriding. What we want to do, is say, if model.Method does not equal to GET, or let’s do it the really proper way, which is equals GET compare OrdinalIgnoreCase, so if it’s GET, even if they’ve missed type the casing, if it’s not GET, we can go ahead and write out the Method. And, in this way we’re only going to include the Method if the Value is not a GET. And we can copy this same behavior by saying, if model IsTemplated, so if isTemplated is true, we can go ahead and expose isTemplated, so the assumption that it would be false if it is not included. When we look at our results now, we’re going to see that the formation of the JSON for the links now only includes self and href, because those are the ones that are going to be simpler and easier to understand, that a GET to the href is going to return this exact object. And that a POST to this href is going to create a new diary entry. This is going to allow us to format what links look like in our actual ending code. So you now have the notion of links across the API, and so we’re really fulfilling the self-describing nature of our REST interface, as well as supporting hypermedia and HATEOAS. Let’s look at the other constraints. Layered System

The next constraint for a REST system is going to be that the system can be layered. In our Client Service constraint we determined that the client and the server were separated, but we really didn’t talk about what was in between the client and server, and so let’s walk through that. The client may be going through the firewall, which can then go through a gateway, which might reach a load balancer, that would then point the request at one or more servers. So, the idea of being layered is that you can have individual responsibilities at different levels of the system. Most likely this is going to be taken care of if the other constraints are there. So, if your system is stateless, or any state you’re using is outside the individual servers, like we did with the caching being in SQL Server, your system can be layered in that way, so that the client doesn’t need to know about the firewall, and the gateway, and the load balancer, in order to perform their actions appropriately. Code On-Demand

Another constraint is the notion of code on-demand, and this is one that’s very rarely used. The idea behind this is - it’s actually mentioned as optional in the original REST paper, and I think there was some hope that there would be usefulness here in some systems. So, the idea behind this is to simply allow the server to supply code that the client could execute. I don’t see this adopted much at all, but in the world of JavaScript, this is something that could actually happen, and could be useful in certain circumstances. I’m not sure that most clients would trust a server to allow them to execute arbitrary code, but you can imagine some cases like validation, where the server could supply some JavaScript that could be used to validate an object before it was sent back to the server. There are cases where that can be useful, but, again, I wouldn’t worry too much about it. REST Maturity Model

So, in building these REST systems, you might be thinking to yourself how much should I be implementing in my particular case. Leonard Richardson came up with something called the REST Maturity Model. You can see a link at the bottom here if you want to read more about it, but the idea is simply that different systems can be talked about as being a certain level of what he calls mature based on certain attributes. So, level 0 is sort of the minimum of any API on the web. You’re doing some API and you’re using HTTP. This could be RPC with XML. It could be RPC in CGI returning binary objects; it doesn’t matter. It’s just saying that you have an API and it’s working over HTTP. Level 1 of the Maturity Model says you’re using resources and identity of resources in your model, so that when you’re going to Food/12 it’s always going to return the food that’s identified by that number 12. Level 2 indicates that you’re using HTTP verbs to do most of the operation, so that a Get, Put, Post, Patch, and Delete all do the sorts of things you would expect from those operations. And level 3 is the HATEOAS or hypermedia level. That is really where you’re going to be supporting hypermedia, self-describing objects, including links to move from state to state in your results. So this Maturity Model can be helpful, but it also can be a cudgel that developers are beaten with. So, I’d like to leave this course with a just a bit of a talk about the pragmatism about this all. The Model is certainly useful, but be careful about using it to grade implementations and developers. When I’m building an API, I take in much of this maturity as I can as is helpful for my API. I want to build just enough maturity into the API that is helpful for the users. So, if I’m using things like a full HATEOAS implementation, and I’m even maybe using code on-demand, I’m probably expecting that the clients for that are going to be fairly automated and sophisticated clients. But, if I’m building a simple API that I’m writing for a simple mobile App, I may only be doing level 1 or level 2. I’m usually starting at least at level 1, and probably level 2 as well, but going down the deep end into the hypermedia probably isn’t necessary for some of the APIs you’re going to be building. I like to say that over-building in API is much worse than under-building, and if we look at versions of different APIs out there, the Twitter API, the GitHub API is a good example, even the Facebook API, you can see that sometimes versions of those APIs tend to be really overly complex, and then they tend to pull back and simplify them. So, I’d rather under build your API than over build. Your users are ultimately who you’re trying to serve, and making it easy for them to implement calls to your API, or fulfilling the requirements of what they’re trying to do is really your goal with an API, not being able to go to a user group or to a conference and say, well, you know my API is a level 3, therefore I’m a smarter or a brighter developer. Please don’t get caught up in worrying about the dogma of the Richardson Maturity Model, or it being in the graces of what we want to call a fully REST-compliant API. You’re writing code to fulfill the requirements of your system, and that’s all. Let’s wrap it up. Summary

So, just to summarize the REST constraints, using the definitions of what a RESTful API is can really help you build a great API that fulfills the needs of your users. By doing this, you’re going to be able to build scalable stateless servers that are going to better serve your users while using the least server resources possible. So, you can scale to the largest number of users possible on the fewest number of boxes. Caching is crucial in most APIs written. In most cases, you should support Caching using ETags, and in order to better serve your users. Again, reducing the load on your servers in supporting things like scaling out of those servers through load balancers, can certainly help you achieve your API’s goals. And by using Links and other methods to make your messages themselves as self-describing as possible, you can enable your users to more easily use your API, and that’s really the spirit of the constraint itself. The REST constraint out there, even though they feel dogmatic, they are ultimately to help build better, easier to use systems. At the end of the day though you have to balance pragmatism and dogma. You have to figure out where on that model is going to best serve your customers, as well as meet your nontechnical goals, like making deadlines, dealing with the limit of developer resources you have, and testing resources, and even machines you have, to be able to deliver a product on time, and usually under budget. Take these constraints as what they are, and that is a guideline to building great scalable systems. Avoid using them as a cudgel to punish your developers, because ultimately if you worry too much about that, you’re going to end up punishing your users by developing APIs that are harder to use. This has been Module 5. My name is Shawn Wildermuth of Wilder Minds. Thanks for joining me. Web API Version 2 Introduction

Welcome to the sixth module of Implementing an API using ASP.NET Web API. My name is Shawn Wildermuth of Wilder Minds. In this module we want to explore the new APIs that have been exposed in the second version of Web API. We’re going to cover what is Web API 2. We’re going to look at how to upgrade a project from Web API 1 to 2, and we’re going to have a deep discussion of attributed routing, or the ability to use attributes to define your routes instead of typical routing. We’re going to look at Cross Origin Resource Sharing and how that’s enabled in version 2. And then finally, we’re going to wrap it up with a new facility in Web API 2 called IHttpActionResult. Let’s get started. What is Web API 2?

So, ASP.NET Web API 2 is a maturation of the existing of the Web API stack. This coincides with the release of ASP.NET MVC5, and is available to anyone using Visual Studio 2012 or 13. It does require .NET 4.5, whereas the prior version would support as low as .NET 4.0, so you’ll have to upgrade your version of .NET as well if you’re not already using .NET 4.5 or 4.51. And, it introduces several new features, which will be useful in your own projects. We’re going to explore some of these, but first, let’s take a look at upgrading our existing project from module five to use Web API 2. There’s a number of pieces that are involved in actually doing this. Converting a Project to Web API 2

So, let’s show you how to convert an existing project to Web API 2. If you want to start a new Web API 2 project, you can certainly do that. You can use both Visual Studio 2012 and 2013 to do that. If you’re using Visual Studio 2013, you’ll simply be able to say, file new project, and when you create an MVC project, it will be MVC5 and Web API 2 by default. In Visual Studio 2012, you’re going to have to create an MVC4 project that includes Web API, and then do a number of steps to upgrade them. Of course, if you want to use Web API 2 and you have an existing project, you’ll have to upgrade, and this upgrade is a step-by-step process. It’s not simply right clicking and saying upgrade to Web API 2. You’re going to have make some changes, and some of them are going to be manual by changing configuration files. But, let’s start with the simpler part of it, and that is making changes to the NuGet packages. So, I’m going to right click the project and just go to Manage NuGet Packages, and I’m going to go to Updates. We’re going to see a number of packages that are updated, but I’m going to focus on the ones that are about upgrading to Web API 2 only. I’m not going bother upgrading jQuery, Entity Framework, and some of the other pieces that may cause some conversion problems. I’m going to focus just on those Microsoft libraries. So, I found a process for doing this. There’s actually a documented process from Microsoft on the ASP.NET website, and I’m going to show you how to do this step-by-step based on those instructions. I’m going to differ from them just a tiny bit, but for the most part, following those instructions is the right thing to do. The first thing I’m going to want to upgrade is actually ASP.NET MVC. Since MVC and Web API are sort of tied together right now, starting by upgrading the MVC will help us upgrade some of packages that we won’t have to manually do, since there’s a lot of dependencies to MVC itself. So I’ll go ahead and hit Update, and it’s going to ask me to approve the License, and there it’s completed the Upgrade. The next step is to actually look for Web API 2, and there’re a number of pieces in here that are Web API. What you want to focus on is the Microsoft Web API 2, and this will say this package contains everything you need to host Web API in IIS. This is the one you want to Update. Again, Accept the License. We’ll also going to want to update the Web API 2 OData libraries. In our particular example, we’re not using the Web API 2 OData, but it contains some other dependencies that are going to need to be updated, so I’d go ahead and Update that as well. Accept that License. And we’re also using CacheCow in our example, so I’m going to Update the SQL Server version, which is going to use the other two parts of CacheCow, so I can Update it in one fell swoop; all done. Another piece we’ll need to Update are the HTTP Client Libraries. Now, as you look through the pages, if you’re a little confused about finding it, you can often just type Search up here to find just the ones that match the substring, and there’s our Client Libraries. We’ll go ahead and Update those as well. And, the last piece of our example is actually uninstalling a package. There is a specific package in here that we no longer need called MVC Fixed Display Modes. This has been depreciated, as we can see here in the highlight, and ASP.NET Web API 2 doesn’t use it, so we’re going to go ahead and Uninstall it. It’s going to ask us to remove these other packages, which we’ll still need, Razor, WebPages, and MVC, so let’s say No to uninstalling them. This way it’s only going to uninstall this package, and not any of its dependencies. We also need to add one package, and that package is the WebHelpers package. You’re going to want the one that’s from Microsoft, Microsoft.ASP.NET.WebHelpers, and the version 3 of that, so let’s go ahead and Install it. At that point, we should be good in NuGet, and, in fact, if we Build, we’re going to get a number of warnings here about remapping the assemblies. And that’s actually the next step of what we’re going to do. Because we’ve upgraded from version 4 of MVC and version 1 and 2 of Web API and some of the core pieces, we’re going to need to change some configurations that tell the App to use specific versions. So, the first piece is I’m going to go into Web.config, and I’ve just formatted it, and I’m going to come down to the bottom, where I have a list of these bindings. Now, if you’re not familiar with the runtime assemblyBinding, the idea behind this is when an assembly is expecting a certain version of a library to exist, this is going to allow you to map with the expected library version to a known version that you are including. So, if we come down here to MVC, we can see that it says for every version up to 4, use the 4 version, in case there’s other libraries that are expecting to use an older version. Because we’re now using 5, we need to change this to 5. The same with WebHelpers. This used to be 1 and 2, and we need this to be 3 now, and 1 and 2 should be 3 for WebPages as well. So, these are the three changes you need to make inside of your assembly to change the versions from WebHelpers 2 to 3, MVC from 4 to 5, and then WebPages from 4 to 5, and make sure that the max oldVersion is going to match what the newVersion is. That’s typically the way these are done, 5 to 5, 3 to 3. In addition to these three assemblies we need to map, we actually have to add a couple more in here that have new versions that there may be inconsistent mappings for. The first one is going to be System.Web.Http.WebHost. This is used by some components, especially CacheCow, so we want to make sure that we’re mapping all versions to the latest version, which is the 5.0.0 version. We’re going to also need System.Web.Razor, and this version is going to be mapping all versions to version 3. And we can make a Copy of this and include also WebPages.Razor, also from 0 to 3, mapping to the 3 version as well. We’re also going to need to do this for a couple of other assemblies we need. One is WebMatrix.WebData, and there we’re going to map that from 3 to 3, and WebMatrix.Data. The last change we need to make here is there’s an App settings near the top that has the value of webpages:Version, and now that you’re using the new MCV5, webpages uses 3 instead of 2, so just make that change. The last piece we need to change is in the Views folder, and we’re looking for the other Web.config. This is Web.config that is specifically for the Views, and it has a number of changes in here around Razor and MVC that all need to be changed from the 2.0 version for Razor, from 4.0 to 5.0 for MVC. So, we can just come in here and make the changes from these three. And your configuration file in your upgrade may be slightly different if you’re not working from our demo, if you’re working from your own project, so be aware that when you make these changes, you want to make sure they are for the correct assembly in the case of MVC or WebPages Razor, or even to System.Web.Razor. We come down here, there’s usually another piece inside the pages element, so we’re going to want to make sure that, because this is MVC, it’s 5, because this is MVC, also 5, and this last MVC also 5. And here in the add assembly, we’re going to go ahead and add that as an assembly type. And that should do it. And now if we Build it, we should get everything running the way we want, and let’s go ahead and run it in the browser. We’re going to see the ASP.NET web page, and let’s go ahead and just go one of our APIs to make sure that they are working as well. So, we now have an ASP.NET Web API 2 running website. Now, we’re ready to go ahead and use some of these new features, which we’ll get to next. Attributed Routing

So, let’s talk about the first new feature in Web API 2 called Attribute Routing. So, here in Visual Studio, if we look at the App_Start, we’re going to remember that there’s this WebApiConfig file that we were using to configure our Routes. So each of the Routes here defined what controller is responsible for what path here. So, you’re able to take an individual controller and determine that when someone goes to this api/nutrition/foods with a foodid that is Optional, that we’re going to use the foods controller, and it’s going to go ahead and find it for us. This is beneficial because you’re defining the Route for an entire controller all at once, and this is a pretty powerful construct, but does occasionally cause problems when you have one controller that may be responsible for multiple types of paths, or when you need some specialized constraints, and you end up creating lots of Routes instead of being able to create Exceptions to Routes. So, in Web API 2, they allow us to use attributes to define the Routes directly on the controller. In order to support this, you’re going to use a setting on the config called MapHttpAttributeRoutes. And what this is effectively doing is saying, go search all the controllers for these attributes that we’re going to use and create Routes for them. The way it’s creating these Routes is a little different as we’ll see in a bit, but let’s see what the functionality does first, and then we can talk about how it works under the covers. These new Attribute Routes actually get in the way of the way we’re doing versioning. We’re doing versioning with our own controller selector. So, for now, we’re just going to comment that out, and we’re going to come back and re-enable this, and show you how the Routes are actually configured under the covers and re-enable this in a couple of videos. Another change we’re going to need to make is we’re going to need to reverse the way that this configuration is called. So, we look at Global.asax, we’re going to see this call to Web Config Register passing in the configuration object. In Web API 2, they’ve actually reversed this. We’re actually going to call GlobalConfiguration, but we’re going to use the method called Configure where we pass it to callback. And, this callback is simply the call to Register inside of our WebApiConfig file. This is simply allowing us to defer when the configuration actually happens. It’s going to happen later in the cycle when Web API is ready for it. This is actually a pattern you’ll see go forward with some of the other configurations that are happening. We’re still calling Register to do the configuration, we’re just doing it whenever the GlobalConfiguration is ready. So it allows them to call it later, instead of us having to do it on Startup. Now that we have that, let’s create a new controller, and I’m just going to call this the StatsController. We’re going to have just a very simple controller here that returns some stats about the data in the database. And if you’ve viewed the rest of the course, you’re going to be pretty familiar with this. We’re going to change it to the BaseApiController that we created. We’re going to generate a constructor that takes in our Repository, and we’re going to pass that Repository into the base class, just so that all that wire up is going to happen. And for us, we’re just going to create a quick Get, to return some standard data from the database. And, I’m just going to Paste in some code here, and this is just going to create a new result object that has the number of foods and the number of users, and then we’re just going to create a response by passing that back to the user of this API. If we go ahead and Build this, and look at this new stats API in the browser, we’re going to see that it’s returning a 404. The reason for that is that we haven’t defined a route for the StatsController. Normally what we would do is go back to the WebApiConfig and create one of these sections for the StatsController. In our case, we’re not defaulting back to a default Route, we’re specifying specifically the Routes we want to get at, so there’s no fallback Route for us to actually use for the StatsController. Instead, we’re going to be using attributes to define the Routes. So here on the Get itself, I’m going to use an attribute called Route, and this Route is going to take the path, and so here I can specifically design the Route to this Get message, to this very specific call on my controller. So, let’s Build it, and we can see it’s now routing directly to that Get because we’re using this attribute to say, hey, the Route for this specific Get call is right here in the Route. So, in a nutshell, this is how the basic Route works. We don’t define the Route in the config file, we instead define the Routes directly in the classes as close to the code as possible. Let’s see what else is available. Attributed Routing Parameters

Next, let’s look at Parameters in Attribute Routing. So here let’s add another method on our controller, and in this case, I’m just creating a Get that has a parameter, an id, and I’m just determining based on what id is passed in what I should do. If 1 is passed in, I’m just going to send it some data about the Foods. If 2 is passed in, I’m sending it some data about the Users. Otherwise, I’m going to return a NotFound here. Attribute Routing’s going to allow me to specify a Route here as well, and I’m going to use curly braces to define parameters to that Route. In this case, I’m going to say whatever is after the slash here, map it to what the ID is here. You’re under the same rules as you saw in typical Web API where it’s going to do its best to map that. So this ID doesn’t have to be an integer, it could be a string, etc. But, in this way I can now, if I Build this, I should now be able to go to 1, and have it show me the number of Foods, and if I go to 2, have it show me the numbers of Users. So, there it’s working. Improved Attributed Routing

So let’s improve how we’re using those attributes. So here in our controller, we can see that there is some duplication of the API, right? We’re repeating this magic string a couple of times, and as a developer that feels a little weird. So, we can actually specify another parameter called RoutePrefix, and this is going to allow us to say that the beginning part of all the Routes for stats is here at the controller level, and then the Route for Get has no on other parameters, and the Route for this Get is just the id. And so, in this way, you’re not repeating any of that information, and later on you could see changing this to a new API and having it cascade to the rest of the Routes very naturally. And, so this feels a lot better. If we Build this, we’ll see our API calls still work. So, go straight to the stats, straight to the number of Foods, and straight to the number of Users. That all works. Great! But, what if we don’t want to use that prefix? They’ve made allowances for that as well. So, let’s say that we have a number of calls here where the RoutePrefix is exactly correct. But I have these couple of Gets down here, or this one Get that I don’t want to use that prefix. I want to be able to define the prefix myself. All you have to do is start it with a tilde character, and it will know that it’s an override. It’ll know that you’re going to start at the root instead of it being relative to the prefix. This should be familiar if you’ve done any ASP.NET work before, because this is the way it also tells it to go to the root of the application for different sorts of links. So, if I say here stat instead of stats, so that I’m looking for an individual stat, I’m telling it to use the prefix for all the Routes, except for this one where I’m making an Exception. So, if I Build it, we can see that stats still works, but that going to stats.1 no longer works. It’s going to give us a 404, because we’ve told it that the real API for each of these stats is just the word stat, and then those will continue to work. You can see now that you can use that prefix to really prevent the repeating of the data, but also be able to override that in cases where you need to have Exceptions to the simple Routing that you may have on the entire controller. It’s important to note that even though one of your calls doesn’t actually extend this prefix, we still need a Route with an empty string in it so that it knows that this is going to be a Routed method. So, by using a prefix, it doesn’t automatically create Routes for each property. You’re going to have to use Route on each property to do those Routes. Attributed Routing Constraints

So let’s talk about constraints next. Over in our controller, let’s create a third call. In this case, I’m going to call Get, but use a string so that I can use the name of foods or users, which may be a little clearer than using the Get with the number. It’s the same functionality, it’s just using a different way to do those lookups. So, let’s go ahead and add a Route, and I’m going to use the same override I did before, stat, but this time I’m going to use name because the name of the parameter is name. These have to match for it to know how to match them up. It’s not doing it by order, it’s doing it by the name of the parameter. So, that’s important that they match. So, by adding this new Get, we should be able to come here and say foods, and we get an error. This error says that more than one actions were found that match the request, because it can’t differentiate which of those two controllers to go after. This is a fairly common problem where you have two methods on a controller that are similar enough that it’s hard for Web API to determine which Route is correct. And so here you can use the constraints. Constraints are added inside of the parameter, and then they’re added as after a colon. So, in this case, we can say alpha, in other words the value we’re looking for is going to be an alpha value, and that inside the ID we can say we expect this to be an integer, because it is an integer. Both these cases we’re using very specific constraints to define which of these to match. This is in essence giving them more information in order to do the match. So, now if we go to foods, we’re getting that match, and users should also work, but also we still have the 1 and the 2 that should continue to work, because we’re calling those second methods. So, in this way you can use those constraints to determine that. There’s actually a wide variety of these constraints. There’re ones for length, for maximum and minimum length. There’s even a regular expression constraint so that you can supply regular expression to match against it, and this can be really useful for when you’re doing things like Slugs and Blogs to make sure that the regular expression is matched for the parameter after a certain API call. If there’s more than one of these, if we had two parameters, we could certainly do this as well, and it would go ahead and use this is a second parameter called date, so you can have more than one parameter inside of a Route, just like in regular ASP.NET Web API. Attributed Routing Names

Next, let’s talk about names when you’re using Attribute Routing. Let’s go ahead and take our Route for Food, and go ahead and comment it out. And we’re going to convert this to using attributes, just so we can see what more of a real world case for this, and where some of the problems can lie, especially when we start to look at the way that names are used. So, to convert our FoodsController, let’s go ahead and give it a prefix. Just like we had before, it’s going to be api/nutrition/foods. So this will be our standard prefix for our individual calls. We only have a couple of calls, so it shouldn’t be that difficult. We’re going to go ahead and create a Route here for the Get, and notice that the Get is empty, but allows two parameters that have default values. Because these are default values, we’re using them in the query string, and we don’t need to accommodate that in the Route. So we can simply say, Route empty in order to get at this, because this is going to be essentially the same as when we call the foods. We also need a Route down here in our second Route, and this is where we’re going to get an individual item, and we’ll go ahead and give it a Route of foodid, again matching the name of the parameter here. And we could do int if we wanted to make sure that there was constraint. Because we don’t need a constraint, I tend to not put them on the Routes unless you need them for differentiation. And so now that we have those, let’s go ahead and Build our project, and let’s go over to nutrition. And we run into this error that says, “A route named food could not be found in the route collection.” Well, we did comment out our route here from the route collection. Who’s actually looking for this? If we dive down into the stackTrace, we’re actually seeing that the ApiController is attempting to get this name somehow. What’s actually happening for us is that when we’re generating this code, we’re using the name of the Route in a couple of places. We’re using it in our URL helper in order to create links for us, and we’ll also using it pretty schematically in our ModelFactory. Let’s look at this Create call in our ModelFactory. We can see that we’re using the urlHelper here with the name of Food in order to create our Link. So, we have to have a Route named Food that we’re going to match here, and the way we can do this is on the controller. Since this is the Route that we’re trying to match, we can add as a named parameter the Name of this Route. By naming this Route, our ModelFactory will be able to find that as a named Route, and then use it in order to construct this urlHelper. If we Refresh this now that we have the name Food in there, let’s see what happens. Now we’re getting the Foods generated, and we’re getting the URLs for the Foods generated correctly. The URLs for the Measures still work because we still have top-level Routes for Measures defined in the WebApiConfig file. But this is being generated directly from our attributed Route. Great, almost. We’re actually missing the href of our next page, and why is that? Let’s back and look. In the FoodsController, when we put together our list, we’re doing a previous and next link, and we’re expecting it to take us to the Food Route. Because we don’t have a specific name of a Route for an entire controller like we used to, we actually need to have a separately named Route here that points to this Route, because this is the Route we’re trying to create a URI for. So, just like before, if we come in here and give it, and I’ll say Foods, since it’s the collection of food, as the name of the Route, and then change Foods in both of these places, we’ll be able to see that the urlHelper is going to construct these URIs for us in the correct way. This is going to the natural foods 1, and this is going to the one with the ID embedded in it. And so to convert our FoodsController over, or our other controllers, we’re going to have to make sure we have these named Routes, and make the changes where we’ve used the names in the correct way. The difference here is we’re no longer mapping to the name of a Route that is specific for a controller, but is actually specific to an individual method on a controller. This is a big change in the way you sort of think about it. You might think, why don’t they just allow us to specify a name when we do RoutePrefix? And the problem there is that that that Route may have these different Routes associated with it, but finding one that matches the URIs may not be as trivial, especially since we can now override the patterns in the Routes based on those prefixes. So, we start to think about Routes being Routes on individual methods instead of the old way, which was always going to be in an entire controller, unless we created multiple Routes per controller, which was much less likely. Often when we think about building these APIs, we think about building a Route per controller, but that doesn’t always hold up. There’s often cases where you’re going to need Exceptions in your API design to allow this. And we’ll actually see this next when we dive in and look at how to make the versioning story work. Advanced Routing

So, let’s look at how the Attribute Routing affects any lower level code you’re working with, like the ControllerSelector that we created in previous modules. If you remember earlier in this module, we had commented out our ControllerSelector. Let me uncomment it, and let’s talk about what’s going on here. If we just Build it and run it, we’re going to get an odd error which says “Value cannot be null,” and when we look at it, it’s actually looking at FindEntry, which comes down to actually TryGetValue, which is a call we’re making inside of our SelectController, inside of the CountingKsControllerSelector. So, let’s see what’s actually happening. Let’s open up the ControllerSelector, and we can see that we’re calling TryGetValue here on the controllerName. If you haven’t seen the versioning module, essentially we’re using the name of the controller to see if there is a new version of that controller, and we have a couple of different ways of determining what the version is, whether it’s from the QueryString, the Header, the AcceptHeader, or from the MediaType. So we expect that we’re going to get an actual controllerName in our Route values. Let’s see what happens there. I’m going to Run this so I can DEBUG it, and let’s go ahead and just Refresh, and what we can see is that the controllerName is null, and the reason is, we are now getting routeData that includes information about what Route it’s trying the match, and we’re going to see that the Route Values for controller doesn’t exist. That’s why this is returning a null value here, as it is correctly converting it into a string, but the value of controller is null, so that there is no controllerName. If we change this to one of the other Routes, like one of the Measure Routes, it simply works. We can see the controllerName here is measures, because when it matched one of the routes defined in the WebApiConfig, one of the old style, it had a name associated with it. So, it went ahead and dealt with the correct Routes so our versioning could run its little code and do its magic. But if we go back to Foods, what we’re going to find in the routeData, and this is where it becomes interesting, is that the routeDate includes several Values of which, if we dig down deep enough, is going to match a controller that doesn’t have a name. Well, that’s interesting. So, we can’t find the controllerName on the routeData. The reason is that our routeData, let’s go ahead and look at the actual Route itself, and this Route is actually something called a RouteCollectionRoute, and this is a Route that contains a number of different Routes. It’s basically a container for other Routes, and there are five Routes in there. That seems odd. Why five? Well, if we look at each of these Routes, it’s going to start to look familiar; api/stats, api/stat/id, api/stat/name, and then nutrition/foods, and nutrition/foods/foodid. So this is one Route collection that’s being treated at the same level as our old Routes that actually has the number of Routes of all the Attribute Routes that were defined throughout our project. And this is the reason why we can’t actually get at the name. This also means that versioning, when you’re using Attribute Routes, can get a little sticky because how do you make this different. We had made a decision in Web API 1 that this was a fine way of figuring out the different version. And we’re going to actually have to determine a different way to do this versioning, and it’s going to depend on your use case exactly how you’re going to do this. You’re still going to be getting that data, but you can’t depend on the controllerName anymore. You’re probably going to have to dig into those, some controller names, and look for those versions as well. In order to get around this and just make the versioning work for our nonattribute Routes, we’re simply going to say, if controllerName string is null, empty, or whitespace. So, if we don’t have a good controllerName, let’s do something different. Otherwise, we’ll go ahead and rely on the other code. Now this module has a lot to cover, so we’re not going to cover how to change it to incorporate versioning for these Attribute Routes. We’re just going to say that we’re not going to use versioning for the Routes that don’t have a controllerName. And all we’ll do is just say return base.SelectController, and pass it in the requests that are being handled. So, it can just select the controller based on those subcontrollers because it already has code in there that supports Attribute Routes. If we make that change, again this means that none of the versioning code is going to run if the Route we’re going against is using an attribute, but that may be good enough for some cases. If we now go back and look at Foods, we’ll see that it now works again. And, if we go to, let’s say, one of the Measures, that will also work, and if we had a specific version for this Measures, it would also work. If we were using one of the versioning techniques, it would still run through that same code. And that is the big story about how Attribute Routing works. On the face of it, it works exactly the way you would expect it to. It’s going to allow you to do Routes at the controller level, and the Routes are going to be closely tied to the actual controller and the controller methods, and that’s actually a pretty good thing. But, any time you’re going to deal with lower end code that’s going to be dealing with Route names, you’re going to have to think about how you’re using those Routes in a different way, and probably use the subroutes in order to get at some of that data. Let’s talk about cross-origin resource sharing next. CORS Support

So, let’s see how Web API 2 has added support for cross-origin resource sharing. Back here in the WebApiConfig, let’s Add support for CORS, as I’ll continue to call it instead of calling it out as cross-origin resource sharing. The idea behind CORS, if you’re not that familiar with it, is simply the concept of allowing other websites to call into your Web APIs. By default, it expects that only calls from either your API or a nonwebsite, like a mobile App, are going to be supported. Browsers typically limit this cross-origin resource sharing, unless you do some handshaking with the original website to make sure that you have rights. And this is where the CORS support in Web API 2 comes in, because it’s a pretty common need. To support this, you’re simply going to call a configuration method called EnableCors. Now when we first add this, it’s going to show us that there is no method called EnableCors, and that’s because it is separated into its own NuGet package. So, if we look for CORS here, we’re going to see the ASP.NET Cross-Origin Support, and then we’re going to see the Web API 2 Cross-Origin Support. This is what we’re actually going to Install. And that’ll bring in both this, as well as the basic ASP.NET Cross-Origin Support, and now we’ll see that that actually gets built. But CORS isn’t enabled yet. It’s only allowing you to enable it on specific calls. So let’s look at our new StatsController, and let’s decide to add it here. We can do this with a new attribute called EnableCors, and that’s going to be in this new System.Web.Http.Cors, and here we’re going to give it three strings. The first string is going to be the origin that is supported. So, I could say that I’m only going to allow foo.com to get at me, or I can also say star, to say, I’m going to allow anyone to get at me, which is often the case. You can also specify which headers are supported, and again you can use star for all, or an empty string or null to not allow any of the specific headers. And this is to enable you to say things like X-OURAPP in order to force whoever’s going to make the call into including a header into your application. I’m going to say it doesn’t matter what headers are there, and then finally what methods. And, here I could say GET and POST if those were the only operations I want, or, again, if I want all, I can just say that. In our case, I’m just going to say GET because we only have Gets. I don’t want them to add more rights than I actually want to allow them to have. If I enable it at the controller level, it’s going to allow it for the entire controller. I could also do this at the Route level if I want to allow it just for some specific methods, or the reverse of that is also to DisableCORS, and this will turn it off for specific calls in our API. So, depending on whether you want to be inclusive, or exclusive, you can kind of decide which mix of these makes the best sense for your implementation of CORS. In some cases, you don’t want to have to go across the entire application and add these, so I’m going to comment this out, and I’m going to allow our entire API to support CORS. And the way we do this, is actually to come in here and say, we’re going to create a new instance of the EnableCorsAttribute, and we’ll need to bring in the namespace for that, and this attribute’s the same as what we would’ve put on top of each of the controllers, or on the specific methods, so it has the same rules that you’re going to need to specify, and then you pass that attribute in, and this is going to use this attribute on every controller automatically. So, in this case, when we Build it, we’re now going to support CORS just by adding these two very simple lines, but we do have the power of using the attribute directly to control what is going to be supported by CORS and what isn’t. Make sense? What is IHttpActionResult?

So, the last feature we’re going to talk about is the IHttpActionResult interface. The idea behind this was to simplify the kind of code you’re writing in your Web APIs. Essentially this interface is used to construct common results that you’re going to return quite often. In many ways inside our APIs, you’re going to use this as a replacement for returning HttpResponseMessages. You’re going to return instead IHttpActionResults. This really is a factory pattern. An object that supports IHttpActionResult is actually a factory for returning an HttpResponseMessage. And the interface looks like this. The object that implements the interface is going to allow it to be called asynchronously, and it’s passed in a CancellationToken, and it expects to eventually get HttpResponseMessage. So, we’re using Task so it is an asynchronous operation, but essentially this is going to generate an HttpResponseMessage, so this is sort of getting in the middle of you constructing them manually. There’s a number of these result types that are already built into Web API 2, including thinks like OkResult, OkNegotiatedContentResult, like the results you see here. For example, the OkResult is a simple way to return the status code of Ok to the client. OkNegotiatedContentResult is a way to return Ok, plus some payload that is negotiated content, and what we mean by that is Web API will look at it, and determine how to serialize that for the client if they’re asking for XML, or JSON, or whatever they’re asking for, it’s going to rely on the formatters to determine how to take that content and send it back. And we can see others here, like NotFound and BadRequest. A lot of these built-in IHttpActionResults are new methods on the ApiController class. So, the ApiController class can now just call Ok, or Ok with some body, BadRequest, NotFound, and there is a handful of these. I’ll let you look at the docs to see them all, but there’re a number of these so that we can simplify the code that we’re writing. And next, let’s look at using the IHttpActionResult. Using IHttpActionResult

So next, let’s see how we would use the IHttpActionResult. Let’s open up our new StatsController and use it as an example. See here in this Get, we’re returning an HttpResponseMessage, and then constructing one from the Request. And this is a lot of glue code that we have to think about. Certainly we could just return the object without using HttpResponseMessage, but if we needed to deal with error conditions, or failures, we couldn’t really do that easily. So instead, let’s pass back HttpActionResult. And, in that case, instead of CreateResponse, we’re simply going to call Ok. We’re going to say, return the HttpActionResult that will return Ok as the status code, and take this content and serialize it to the user. If we do the same thing here, then again these become Ok, which is nice and simple, right? It’s a little cleaner about what we’re actually doing. And then instead of returning response with NotFound, we can simply say NotFound, and so the result of the design and the implementation of our methods on our controllers ends up being a lot clearer and a lot more self-describing. And, I’ll repeat that here. Most of the kinds of standard status codes you’re used to returning are going to be included here. So we could certainly do NotFound, but we also could do BadRequest, InternalServerError, etc. So, there’re a number of these you’re going to want to look at the documentation to see all the different IHttpActionResults that you can return directly, because we’re using the ApiController. But where could we use this IHttpActionResult in our own code? The idea behind its use is not only that we want to return and truncate our code here so that we’re a little clearer about what we’re doing, but we also want control over constructing the response message. And, so it may be that you want to be able to send certain things, and a common case of this is either you want to control serialization, or you want to control headers that are sent back, and instead of repeating that code over and over and over again, we can actually create one of these IHttpActionResults that will package that up in a pretty simple way. Let’s do that. I’m going to start by creating a new folder because we may have a handful of these results. So, I’m going to create an ActionResults folder for us to hold these individual action results in. And I’ll Add a new Class here, and I’m going to call this VersionedActionResult, and I’m going to derive this from IHttpActionResult, which is in System.Web.Http. I’m also going to implement the interface so that I can actually see what we’re doing here, and I’m going to clean up the code by importing some namespaces, because it makes me crazy that it doesn’t do this for me, so that we have our task that goes and Executes in order to return us an HttpResponseMessage. So, we’re going to want a constructor here, because we’re going to need some pieces of information for our versioned results. We’ll probably going to need an HttpRequestMessage. We’re also going to need a string that represents the version that we want to add on to the response message, and we’re finally going to probably want somebody that we’re going to send back that will versioned. And because of this we’re actually, and in my case, we’re going to use a generic version of this class, where T is some object. So, it’s going to be a class and I’m going to allow it to be passed in to our versioned result and then I’ll go ahead and very quickly store these locally, and so there we simply have our constructor, and the three pieces of information we need to actually implement calling and constructing our response message. So, to implement this, we’re simply going to take the request and call CreateResponse using the body as the content of that response, so that we’re creating the response message we want to send back with the body content of what we want it to actually serialize. And here is where we’re going to do our special piece of code. We’re going to go ahead and add some specialized header. We don’t really have a use for this, but this is to show you what’s really going on, and we’re going to pass in that version that was being given to us from the constructor, and then we’re going to use Task.FromResult to tell it to return a Task with some body content. In this case, we’re doing this pretty synchronously, but the interface requires it to look and pass back a Task, so we’re going to go ahead and allow that by just Task.FromResult. Sometimes this is going to be an operation that is asynchronous, and so you could certainly use async and a wait in order to do this. Now that we have the result, what do we do with it? Let’s go over to our BaseController, and let’s add support. I like doing it here, that way we don’t have to pass in too many pieces from our code. We want our code to be nice and clean. So, in order to allow this, we’re going to create a new protected call, that’s going to return an HttpActionResult, and this is just going to be something that’s going to allow the controllers themselves to call this. And I’m just going to say Versioned, and here we’re going to allow them to pass in a generic version of the content that they want to send, and then the version. Now, in our case, we’re going to default it to be version v1, so that they only need to specify it if they want to override that version. And returning this is simply just saying return new VersionedActionResult, and we just need to tell it that this is a class for our generic argument here, and then we’re just going to simply return a new instance of our action result, by passing in our Request, which we already have access to, the version, and then the body. And let’s make sure it’s using the generic version, bring in the action results namespace, and now we’ve added this to our Base API, so that we can now, anywhere we need to return a version header, let’s say in Foods, instead of returning a FoodModel, we can go ahead and return an HttpActionResult, and then simply wrap this in Versioned. And, in this way you’re individual methods on your controllers won’t need to think about manipulating the headers individually. And make sure it’s built, and if we head over to Fiddler, we have our call to an individual food. Let’s Execute that, and we’ll see that it returned a 200. If we look at the result, the Raw result, we’ll see right here is OurVersion at v1. If we come back here, and change that version, again, this is allowing us to just pass in whatever version information we want, and we re-execute this call, we’re going to see we now have OurVersion 2 as that header being injected in. So the result of this is that we’re able to add a very simple way using IHttpActionResult way to wrap this common functionality that you may need throughout our Web API solution in order to do things like manipulate the data types that are being returned, manipulate the way the formatters work, or ultimately be able to change the headers as well. Let’s wrap up this module. Summary

So, we’ve taken a look at Web API 2 and looked at some of the key features that are important to building your own APIs. Hopefully, you’ve seen that the Framework is maturing at a pretty steady pace. It’s adding some key features that are going to make your code more readable, give you more flexibility about Routing, as well as enable common features like CORS. Attribute Routing is pretty simple to use, and certainly easy, and will get you over the first hump with defining Routes at either a method level or allowing you to specify with some other features, like RoutePrefix, that you want common Route paths for entire controllers. You do have to remember that Attribute Routes are treated differently, so any lower code you’re dealing with, you’re going to have to remember to dig into the subroutes to find the Routes that are using attributes. We’ve also seen that the CORS support is certainly simple. It’s easy to opt-in, and it’s becoming a pretty major use-case where you want to be able to expose in API the other websites used. It’s now just a couple lines of code to enable that, whereas before it was finding and writing code. We’ve also seen that the IHttpActionResult changes can certainly make your code more readable and more testable, so that you can go ahead and write code that is easier for people to follow, and certainly more self-describing than it used to be. We’ve also seen that we can build our own action results to solve common structural problems, where we want to return standard headers, where we want to be able to manipulate the results of what we’re doing. It’s pretty easy to build these action result handlers, and just simply wrap them when we return a result inside of our controllers. Well, this has been Module 6 of Implementing an API Using Web API. My name is Shawn Wildermuth of Wilder Minds. Thank you.