I
I
Ilya Trifonov2018-02-09 16:38:19
Angular
Ilya Trifonov, 2018-02-09 16:38:19

SPA router in ASP.NET Core Web API?

Hey!
The case is as follows:
There are two projects - ASP.NET Core Web API (hereinafter referred to as Server) and Angular 5 (hereinafter referred to as Client). Client can build in the wwwroot folder, so that later you can run only one Server project in production and everything will work. The router I use is from Angular. After building to the wwwroot folder, further navigation within the application works properly.
For example:

  1. The user went to localhost:5000
  2. The user navigates to localhost:5000/about using the button in the navigation menu
  3. The About page is rendered to the user

And everything seems to be fine, but... If you make a refresh at the address localhost:5000/about , an error 404 crashes. I can roughly imagine why this happens (there is simply no about.html page on the server), but I don’t know how to fix it.
Startup.cs settings:
public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(o => o.AddPolicy("Base", builder =>
            {
                builder
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .WithOrigins("http://localhost:4200");
            }));

            services.AddSignalR();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseDefaultFiles();
            app.UseStaticFiles();

            app.UseCors("Base");

            app.UseSignalR(routes =>
            {
                routes.MapHub<ChatHub>("chat");
            });
        }
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MrDywar Pichugin, 2018-02-09
@ilyatrifonov

I faced such a problem when I did the first SPA.
Here are the solutions:

1) Установить url rewrite на IIS
  http://stackoverflow.com/questions/35319942/url-rewrite-does-not-install-on-windows-10-iis-10
2) How do I configure IIS for URL Rewriting an AngularJS application in HTML5 mode?
  http://stackoverflow.com/questions/12614072/how-do-i-configure-iis-for-url-rewriting-an-angularjs-application-in-html5-mode
  https://www.youtube.com/watch?v=KprM27YP89Q&list=PL6n9fhu94yhWKHkcL7RJmmXyxkuFB3KSl&index=29
3) 
  3.0 Сделать точку входа с префиксом, например /app/
    Добавить в <head>:
    <base href="/app/" />
    На всех ссылках href тоже добавить /app/, или можно этого не делать и когда в href="movies/add" путь не начинается со слеша, то /app/ добавляется автоматически из <base .. />
    , в MVC route добавить первым маршрут:
    routes.MapRoute(
                  name: "Angular",
                  url: "app/{*anything}",
                  defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
              );
    Это позволит на все обращения site/app/ всегда отдавать /Home/Index - в котором находится точка в хода в приложение.
    Таким образом мы никогда не выйдем из приложения, а все другие ссылки должны быть без /app/.
    Ангуляр уже сам разрулит что там отображать исходя из $location.
        
  3.1 Добавить в web.config правила
    <system.webServer>
      <rewrite>
        <rules>
        <rule name="AngularJS Routes" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          <add input="{REQUEST_URI}" pattern="^/(bundles)" negate="true" />
          <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
          </conditions>
          <action type="Rewrite" url="/" />
        </rule>
        </rules>
      </rewrite>
    </system.webServer>
  3.2 Использовать OWIN Middleware который будет это делать C# кодом. OWIN middleware to support html5 routing.
  3.3 Использовать свой mvc route provider.
  3.4 Another way to use ASP.NET MVC and add to RouteConfig.cs: routes.MapRoute(name: "Default", url: "{*anything}", defaults: new { controller = "Home", action = "Index", } ); and your HomeController Index just returns File("~/index-anyhinghere.html", "text/html"); Then your app becomes IIS independent

Each solution number is independent, you do not need to do several at once.
I use 3.0
Convenient and simple.
All popular SPA sites just use '#' to support older browsers.
The feature of SPA is that it doesn't reload the page. The browser, when changing the URL, actually stands still, at Index/Home. Angular pulls pieces of HTML through Ajax on its own and displays it on the same page - the old one was erased, the new one was added.
If you press F5, then all Javascript state will be lost, local / session storage is suitable for saving data between F5.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question