Converting Our Project to a Web App3:47 with James Churchill
Now that we have our console app project, let's see what it takes to convert it to a simple web app.
Let's convert our console app project to a simple web app. 0:00 We'll start by adding a dependency for Kestrel. 0:03 Remember, Kestrel is the cross-platform managed web server for 0:06 hosting ASP.NET Core apps. 0:11 First, we add the name of the new get package. 0:14 Microsoft.AspNetCore.Server.Kestrel. 0:18 Then we provide the version number that we want to use. 0:26 Which in our case is 1.0.0. 0:30 When we save the file, code will recognize that we just added a new dependency, 0:34 then ask if we want to run the restore command. 0:38 Next, we'll open Program.cs and make some modifications. 0:42 First, we need to add the following name spaces, 0:50 using Microsoft.AspNetCore.Hosting. 0:55 Using Microsoft.AspNetCore.Builder. 0:59 Then using Microsoft.AspNetCore.Http. 1:05 Then in the main method, we need to instantiate and configure the host for 1:11 our web app. 1:16 Var host = new WebHostBuilder. 1:20 We need to tell the host to use Kestrel as the server by calling the UseKestrel 1:25 extension method. 1:29 Then we configure the host by calling the Configure method. 1:32 The Configure method expects a delegate that accepts a parameter for 1:38 the IApplicationBuilder instance. 1:42 Which we can use to configure our app. 1:44 On the app builder, we call the Run method. 1:48 The Run method also expects a delegate that accepts a parameter for 1:56 the HTTP context for the current request. 2:00 The context gives us access to the Response. 2:05 On which is an extension method, WriteAsync, 2:09 that allows us to write asynchronously to the response body. 2:12 Our Run delegate represents a very simple middleware component. 2:21 We'll see more examples of ASP.NET Core middleware later in this workshop. 2:25 Lastly, we Build and Run the host. 2:30 Now we can press F5 to run our application. 2:37 Once the application has been started, we can browse to the URL localhost:5000. 2:44 And here's the output from our middleware. 2:54 When you create a web app project using the .NET CLI or the full version of 3:01 Visual Studio, the contents of the Program.cs file will be provided for you. 3:05 So you typically won't write this code yourself. 3:11 That being said, you can see that it's relatively easy to get a web app host and 3:14 server up and running. 3:18 Also, our web app isn't very indicative 3:20 of what a typical ASP.NET Core web app looks like. 3:23 Rather, this is an example of the smallest, 3:26 simplest web app that you can build. 3:29 Though it's not a very practical solution. 3:31 For instance, most ASP.NET Core web apps will use MVC 3:34 instead of directly writing to the response body, as we did here. 3:39 We'll see an example of an MVC web app in the next video. 3:43
You need to sign up for Treehouse in order to download course files.Sign up