It’s video time!

On one of the recent ASP.NET Community Standup videos (found here), Scott Hanselman noted that folks were interested in seeing more video tutorials, and not just videos for beginners.

In the budgeting app series, I created a pure (non-MVC) React client app in a separate project, on a separate kestrel server than the Web API it communicated with for data.

But how do we serve both the site and the Web API on the same server under the same port and avoid the cross-origin resource sharing issue?

A user on reddit recently asked this same question. He didn’t want to use MVC routes and razor pages. In the video below I walk thru a quick Web API project setup and the additional step of serving an html file from the web root.

I’ve summarised it below the video in case you don’t want to watch.

I start from scratch and create a new ASP.NET Core Web API project using Yeoman. You can also just do this with Visual Studio, choosing the Web Application project type and selecting the Web API template.

Once your project is stubbed out, you’ll only need to add a few things.

First, add your default index.html file to the project’s wwwroot folder. Something like the below is fine:

<html>
  <head></head>
  <body>
    <h1>Hello World!</h1>
  </body>
  </head>
</html>

If you run the project now with dotnet run you’ll notice it still doesn’t serve the html at the root.

To get this to work, you’ll need to instruct the server to serve static files from the web root folder. On top of that, you’ll need to instruct it to serve default files. It doesn’t know what to serve by default, so you’ll use a line of code that tells it to look for index.html.

First, add the static files reference to your project.json (soon to be .csproj):

"Microsoft.AspNetCore.StaticFiles": "1.0.0"

Then, add the using Microsoft.AspNetCore.StaticFiles; line to the top of your Startup.cs file, and also add the below two lines to the Configure() method, before the UseMvc() call:

app.UseDefaultFiles();  //enables server to look for index.html.
app.UseStaticFiles();   //enables server to serve static files from web root instead of just MVC routes.

One other thing you may need to do (it was auto-generated for me) is declare the content root as the current directory in your Program.cs file like so:

  var host = new WebHostBuilder()
                .UseConfiguration(config)
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())  //this line.
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

That’s it.

Give it a dotnet restore and dotnet run to see that our html file is now served and the web API is available as well.

Let me know in the video comments if you like this format. You can also tweet me or comment on the reddit post.