Skip to content

Instantly share code, notes, and snippets.

@kentcooper
Last active November 1, 2023 08:52
Show Gist options
  • Save kentcooper/88d99c258b041f335c98 to your computer and use it in GitHub Desktop.
Save kentcooper/88d99c258b041f335c98 to your computer and use it in GitHub Desktop.
Creating a SPA Host Owin Middleware
using System;
using System.IO;
using Microsoft.Owin;
using Microsoft.Owin.FileSystems;
using Microsoft.Owin.StaticFiles;
using Owin;
namespace Infrastructure.Owin
{
public static class SpaHostExtension
{
public static IAppBuilder UseSpaHost(this IAppBuilder builder, string rootPath, string route, string entryPath)
{
var options = new SpaHostOptions
{
FileServerOptions = new FileServerOptions
{
EnableDirectoryBrowsing = false,
FileSystem = new PhysicalFileSystem(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, rootPath))
},
EntryPath = new PathString(entryPath),
Route = new PathString(route)
};
builder.UseDefaultFiles(options.FileServerOptions.DefaultFilesOptions);
return builder.Use<SpaHostMiddleware>(options);
}
}
}
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.Owin;
using Microsoft.Owin.StaticFiles;
namespace Infrastructure.Owin
{
public class SpaHostMiddleware
{
private readonly StaticFileMiddleware _innerMiddleware;
private readonly Func<IDictionary<string, object>, Task> _next;
private readonly SpaHostOptions _options;
public SpaHostMiddleware(Func<IDictionary<string, object>, Task> next, SpaHostOptions options)
{
_options = options;
_next = next;
_innerMiddleware = new StaticFileMiddleware(next, options.FileServerOptions.StaticFileOptions);
}
public async Task Invoke(IDictionary<string, object> environment)
{
IOwinContext context = new OwinContext(environment);
Trace.WriteLine("Entered SpaHostMiddleware Invoke");
Trace.WriteLine(string.Format("Route: {0}, Path: {1}", _options.Route, context.Request.Path));
if (context.Request.Path.StartsWithSegments(_options.Route) || _options.Route.Value == "/")
{
Trace.WriteLine("Handling Route");
context.Request.Path = _options.EntryPath;
await _innerMiddleware.Invoke(context.Environment);
}
else
{
await _next.Invoke(environment);
}
}
}
}
using Infrastructure.Owin;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(Startup))]
namespace Website
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseStaticFiles("/content")
.UseStaticFiles("/app")
.UseStaticFiles("/img")
.UseStaticFiles("/scripts")
.UseStaticFiles("/components")
.UseStaticFiles("/samples")
.UseSpaHost("", "/subspa", "/subspa.html")
.UseSpaHost("", "/", "/index.html");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment