Skip to content

Commit

Permalink
WIP SPA routing
Browse files Browse the repository at this point in the history
  • Loading branch information
gabrielweyer committed Nov 26, 2018
1 parent ccdb762 commit 076e2d8
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ I'm also shamelessly promoting some of my projects that nobody else is using (in
## ASP.NET Core and Angular cookbook

- [Mitigate CSRF](docs/aspnet-core/csrf/README.md)
- [SPA routing](docs/aspnet-core/spa-routing/README.md)

## Instant nuggets

Expand Down
45 changes: 45 additions & 0 deletions docs/aspnet-core/spa-routing/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# SPA routing

I like separating the `SPA` and `API` codebase (they could still live in the same repository but in different directories). If you do end up deploying the `SPA` in the `wwwroot/` directory of the `API`

```csharp
public class SpaRoutingMiddleware
{
private readonly RequestDelegate _next;

public SpaRoutingMiddleware(RequestDelegate next)
{
_next = next;
}

public Task InvokeAsync(HttpContext context)
{
if (IsGetMethod(context) && !IsApiPath(context) && !HasExtension(context))
{
context.Request.Path = "/index.html";
}

return _next(context);
}

private static bool IsGetMethod(HttpContext context)
{
return context.Request.Method == HttpMethods.Get;
}

private static bool IsApiPath(HttpContext context)
{
return context.Request.Path.StartsWithSegments("/api");
}

private static bool HasExtension(HttpContext context)
{
if (!context.Request.Path.HasValue)
return false;

var startIndex = context.Request.Path.Value.LastIndexOf('.');

return startIndex >= 0;
}
}
```

0 comments on commit 076e2d8

Please sign in to comment.