0

i'm trying to build a web app with asp.net core for back-end side and angular 1.5.x for front-end side. the problem is haw to enable angular routes to be analyzed by the server. i added these lines of code to the startup.cs and evry thing works fine:

 DefaultFilesOptions options = new DefaultFilesOptions();
            options.DefaultFileNames.Clear();
            options.DefaultFileNames.Add("Index.html");
            app.Use(async (context, next) =>
            {
                await next();

                if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
                {
                    context.Request.Path = "/Index.html";
                    await next();
                }
            })
            .UseCors("AllowAll")
            .UseDefaultFiles(options)
            .UseStaticFiles()
            .UseIdentity()
            .UseMvc();

but i looks like it's not a good practice, and this problem should be solved in the appsettings.json. any ideas ?

6
  • Use JavaScriptServices: github.com/aspnet/JavaScriptServices they add both server-sided nodejs (including angular) rendering as well as enables a default route which will route first-time calls to the index/home/whatever page where the SPA is embedded. All conclusive calls are handled by the angular router Commented Mar 21, 2017 at 9:08
  • @Tseng haw to do it with the appsettings.json file ? Commented Mar 21, 2017 at 9:32
  • Why? It's very unlikely you gonna change the route/controller on the run. Angular SPAs just need a single entry point (that's where the name comes from Single Page Application) Commented Mar 21, 2017 at 9:37
  • @Tseng haw to told the server to use the entry point ? as if you say evrything will work automatically ! Commented Mar 21, 2017 at 10:33
  • i added Microsoft.AspNetCore.NodeServices , Microsoft.AspNetCore.SpaServices and Microsoft.AspNetCore.AngularServices packages, it works fine but i have an exception adding the Mvc in startup.cs Commented Mar 21, 2017 at 10:36

1 Answer 1

1

The answer (mostly) is in the UseMVC options... you should implement server-side routes as shown

    app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");

    routes.MapSpaFallbackRoute("spa-fallback", new { controller = "Home", action = "Index" });
});

look at this link

Sign up to request clarification or add additional context in comments.

1 Comment

I said (mostly) because I never tested it but I think it's a reasonable answer...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.