Develop an ASP.NET API site together with an Angular JS frontend

Recently I’ve started to play around with Angular JS and ASP.NET core. I’ve created an ASP.NET web API project and (basically) copied the Angular frontend to wwwroot.

All Angular stuff is running by using an index.html file containing the app and all pages are displayed by using an MVC like scheme (aka API calls to the backend services are encapsulated within the path /api (e.g.

After creating a web API project with Visual Studio, it’s not possible to drive static files which are copied to wwwroot. Therefore two more lines are necessary to drive files from within an API app. Please add the following lines before the app.UseMvc() call in Startup.cs:

// switch to index.html on any request not starting with "api/"
// (C# controller) nor being an existing static file
app.Use(async (context, next) =>
    await next();
    var path = context.Request.Path.Value;
    var fileInfo = env.WebRootFileProvider.GetFileInfo(path);
    if (!path.StartsWith("/api", StringComparison.InvariantCulture)
        && !fileInfo.Exists)
      context.Request.Path = "/index.html";
      await next();

The first statement (app.Use(...); ) will handle all not known requests to the backend and route them to index.html (e.g. the angular router will handle the request).

Any request that is not routed via api  and that does not map to an existing file under wwwroot  will be forwarded to index.html. Routing errors (e.g. invalid pages, …) are forwarded to /404 .

app.UseDefaultFiles() will check for default files if a root path or directory is given. In the current scenario this will work only for the root directory which is sufficient.

app.UseStaticFiles() is responsible to serve all files located under

Example code can be found at

Leave a Reply

Fill in your details below or click an icon to log in: Logo

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.