If you want to host your SPA app on .NET Core you’ll need to make sure your application is set up to serve your SPA’s static html and javascript files.

First of all make sure you’ve got a .NET Core web application up and running.

There are two ways to serve the initial page for your SPA.

  1. Use a static html page
    2) Use an MVC controller to return a view

If you want to use an MVC controller and a view, check out adding MVC to your ASP.NET Core web application.

Even if you do decide to use MVC to serve the view, you’ll still need to serve static files for your javascript. Read on to find out how.

Serving static files

Start off by creating a wwwroot folder in the root of your web app and create an index.html file inside it.


Update

Bastien rightly pointed out (in the comments) that this will already be set up and working if you used the ASP.NET/MVC template to create your Core app. If you’ve followed the previous posts and/or set up your Core app from scratch without using the template, then you’ll need to manually configure Core to serve static pages. Read on to see how.


If you run your app and try to access this index.html file you’re out of luck. The file will not be served.

By default ASP.NET Core does not serve static files. To change that you need to make a few changes.

Start off by bringing in the static files dependency.

dotnet add package Microsoft.AspNetCore.StaticFiles -v 1.1.*

Remember to run dotnet restore after adding dependencies.

Update the Configure method in Startup.cs to add the UseStaticFiles Middleware.

public void Configure(IApplicationBuilder app)
{
  app.UseMvc();
  app.UseStaticFiles();

  app.Run(context => {
      return context.Response.WriteAsync("Hello world");
  });
}

Finally make sure you’ve specified a ContentRoot in Program.cs.

public static void Main(string[] args)
{
  var host = new WebHostBuilder()
  .UseKestrel()
  .UseContentRoot(Directory.GetCurrentDirectory())
  .UseStartup<Startup>()
  .Build();
  
  host.Run();
}

By default the static files middleware will now serve static files contained within the wwwroot folder.

Run your app (dotnet run) and you’ll be able to access your static page in the browser.

http://localhost:5000/index.html

Note, you don’t need to put wwwroot in the url, in fact if you do, it won’t work.

You can now put any static files (css,js, images) in wwwroot and they will be accessible by your SPA.

Source code, step-by-step tutorials, videos and more

I've compiled a whole load of useful tutorials, source code for articles (like this one) and mini video series to help you push through all the noise and build better ASP.NET web applications, faster.

Drop your email in the box below to get new posts first, and instant access to 'the vault'.

I respect your email privacy. Unsubscribe with one click.