Notes from building a first ASP.Net Core App (part 5)

  1. Be default, and Empty ASP.Net Core application does not actually serve up html pages. You have to add that to the pipeline.
  2. To prove this, add an html page to the wwwroot folder, run the application and try navigating to the page. It will return the default web site, in the state you last left it in. The html page won’t show.
  3. To get static content to be shown will require the Microsoft AspNet Static Files middleware. This is installed via a Nuget package. Right-Click on the Package Manager, choose Browse, then type static files. Select “Microsoft.AspNetCore.StaticFiles” from the list and install it. Agree the the licence blindly (like you always do.)
  4. Go into the Startup class and add the following pipeline statement:

    Put it just before the app.Run statement.

  5. Run the application, and it will show the site just as before. Navigate to the html page and viola, it renders!
  6. What happens is that when it hits the Static Files middleware, it will look for the file in the file system, and if it finds a static file match, it will render it and return. Otherwise, it will continue through to the app.Run.
  7. This is really important, because without it, you won’t be able to run html, javascript or css files. Your Angular files won’t run!
  8. If you want it to use the standard default files usually associated with a web site, you need to add another piece of middleware just before executing the UseStaticFiles method.
  9. To do that, add UseDefaultFiles method to your code:
      public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IMyCustomConfiguration myCustomConfiguration)
                if (env.IsDevelopment())
                app.Run(async (context) =>
                    var newHelloWorldMessage = string.Format("Hello World! Your text was >{0}<", myCustomConfiguration.GetMyCustomMessage());
                    await context.Response.WriteAsync(newHelloWorldMessage);

    This will now automatically redirect you site to files like default.html, or index.html.

  10. But that’s not all. You don’t actually need those two lines. You can replace them both with:

    which will perform the same job.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: