With RC1 of ASP.NET Core 1.0's MVC 6 you can map routes from within your Startup.Configure
function when invoking app.UseMvc
. I have mapped a "spa-fallback" route that will ensure that the HomeController
and Index
view are the defaults like so:
public void Configure(IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
// ... omitted for brevity
app.UseExceptionHandler("/Home/Error");
app.UseStatusCodePagesWithRedirects("/Home/Error/{0}");
app.UseMvc(routes =>
{
routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
routes.MapRoute("spa-fallback", "{*anything}", new { controller = "Home", action = "Index" });
routes.MapWebApiRoute("defaultApi", "api/{controller}/{id?}");
});
}
I desire the fallback so that my Angular2 app's routes will not result in an HTTP Status Code of 404, Not Found. But I also need to correctly handle when a user does inadvertently attempt to navigate to a page view that doesn't exist. You might notice that I have also called app.UseStatusCodePagesWithRedirects("/Home/Error/{0}");
.
The call to redirect to my error page with the status code and the "spa-fallback" route seem mutually exclusive -- meaning it appears that I can only have one or the other (but sadly not both). Does anyone know how I could manage to have the best of both worlds?
It took me some time to figure out how to do this without serving my index using MVC and to still receive 404s for missing files. Here's my http pipeline:
I came up with two possible workarounds/solutions.
ASP.NET Core 1.0, RC1
With Angular2 specifically, we can simply swap out the
LocationStrategy
. For example in mywwwroot/app/boot.ts
I have the following:Note that I am utilizing the
provide
function to override the standardLocationStrategy
with theHashLocationStrategy
. This adds the#
in the URL and prevents MVC from incorrectly throwing 404's, but also correctly handles responding with 404's when the user manually types in a URL that doesn't exist.ASP.NET Core 1.0, RC2
Simply use
Microsoft.AspNet.NodeServices
. Within this library there are bothAngularServices
andReactServices
which allow for the mapping of SPA routes specifically, via theMapSpaFallbackRoute
function. I state that we need to wait for RC2 with the understanding that the current implementations are not fully functioning as desired.Try this:
app.Run() will catch all requests that doesn't match any of the routes defined earlier. This way you can get your custom spa fallback and use app.UseStatusCodePagesWithRedirects() at the same time.