Join Michael Sullivan for an in-depth discussion in this video Create a custom route, part of ASP.NET MVC 5 Essential Training.
- [Instructor] So we've seen what the default route looks like. Let's add a custom route now. For this scenario we want to have a Backstage Pass that our special fans can get if they know a secret password. The way we're going to do that is we're going to add a route to let them get to this. I'm going to add a route. I'm going to copy the one that's here. Let me just get a little more screen real estate here by minimizing that. I'm going to take this route and I'm going to copy it. So I've got that to start from and I'm going to call this my Backstage Pass.
In order to get into the Backstage Pass you're going to need a URL that's going to go from the Backstage. And what we're going to do is we're going to have Backstage and then we're going to require you to have the secret, and that secret is something that you'll need to type in and include when you come to this and then we'll have a format that you can optionally say, what do you want this to be returned as? In our defaults, I'm going to use the home controller still. I'm going to call this Backstage as the action that we're going to take.
And then I'm going to have the default be the format. It's going to be an optional parameter. Now that I've added this we'll go into the controller and add our Backstage action. So down here under the contact, I'm going to add my action. Public ActionResult, and we're going to call this Backstage. And we'll scroll down a little bit.
And inside here what I'm going to do is I'm going to say if, secret is not equal to special, do you have the special secret? Then we're going to return a new HttpStatusCodeResult. And we're going to return a 403 which is a forbidden. Otherwise we'll return a view for our Backstage. Now that view, what is it going to look like? Well we can right-click in here and say add a view.
We're going to just do an empty view. We're going to just use the defaults. What this does is it adds to my views folder, a Backstage view and in the Backstage you'll say, You Rock! And then in our Solution Explorer if you come down you'll see down here, it's now got the Backstage View added to our Home folder. So let's try this out. I'm going to run this without debugging by going to Debug, Start Without Debugging. And you'll notice that it's going to give me the forbidden because I don't have permission.
I didn't put the right password in so we'll put inside of my route, Backstage, and then my special password. And if I do that then you get into the Backstage. Now if I had the wrong password, then you're going to get a forbidden.
- Creating a new ASP.NET MVC 5 project
- Building custom routes
- Creating custom layouts
- Adding a model to a view
- Deploying to Azure and Amazon Web Services
- Configuring authentication and authorization
- Unit testing code