Created
March 27, 2017 17:55
-
-
Save DamianEdwards/a8b67a66f60d3358734ef1059357c125 to your computer and use it in GitHub Desktop.
Simpler ASP.NET Core startup?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Task; | |
using Microsoft.AspNetCore.Builder; | |
using Microsoft.AspNetCore.Hosting; | |
using Microsoft.AspNetCore.Http; | |
using Microsoft.Extensions.DependencyInjection; | |
namespace HelloWorld | |
{ | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
// Step 0: Single line Hello World | |
// Runs using Kestrel on port 5000 | |
WebHost.Run(context => context.Response.WriteAsync("Hello, World!")); | |
// Step 1: Change the listening port | |
// Runs using Kestrel on specified port | |
WebHost.Run(8080, context => context.Response.WriteAsync("Hello, World!")); | |
// Step 2: You need to add middleware or anything else | |
// Configure returns an IWebHostBuilder so now you're into the standard pattern | |
WebHost | |
.Configure(app => | |
{ | |
app.UseStaticFiles(); | |
app.Run(context => context.Response.WriteAsync("Hello, World!")); | |
}) | |
.Run(8080); | |
// Step 3: When you want to run things that need services, e.g. MVC/dynamic server-side HTML (Razor Pages), Authentication, etc. | |
// ConfigureServices returns an IWebHostBuilder so now you're into the standard pattern again | |
WebHost | |
.ConfigureServices(services => | |
{ | |
services.AddMvc(); | |
}) | |
.Configure(app => | |
{ | |
app.UseStaticFiles(); | |
app.UseMvc(); | |
}) | |
.Run(8080); | |
// Step 4: You add logging and configuration | |
// Now we're starting to get to something truely useful | |
WebHost | |
.ConfigureServices(services => | |
{ | |
services.AddMvc(); | |
}) | |
.Configure(app => | |
{ | |
app.UseStaticFiles(); | |
app.UseMvc(); | |
}) | |
.UseLogging(logging => logging.AddConsole()) | |
.UseConfiguration((builder, env) => | |
{ | |
builder.AddJson("appsettings.json"); | |
if (env.IsDevelopment()) | |
{ | |
builder.AddUserSecrets(); | |
} | |
builder.AddEnvironmentVariables() | |
.AddCommandLine(args) | |
}) | |
.Run(8080); | |
// Step 5: You want to move to a Startup class | |
// All the services & HTTP stuff has moved to your Startup class | |
WebHost | |
.UseStartup<Startup>() | |
.UseLogging(logging => logging.AddConsole()) | |
.UseConfiguration((builder, env) => | |
{ | |
builder.AddJson("appsettings.json"); | |
if (env.IsDevelopment()) | |
{ | |
builder.AddUserSecrets(); | |
} | |
builder.AddEnvironmentVariables() | |
.AddCommandLine(args) | |
}) | |
.Run(8080); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment