Search code examples
asp.net-coreurl-routingsingle-page-applicationmiddlewareasp.net-core-2.1

.Net Core Spa Resource Routing on Relative paths


I have the following .net core spa application configured

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseSpaStaticFiles();
        app.UseCookiePolicy();

        app.UseAuthentication();


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


            routes.MapRoute(
                name: "catch",
                template: "{*url}",
                defaults: new { controller = "Home", action = "Index" });
        });

        app.UseSpa(spa =>
        {
            spa.Options.SourcePath = "Spa";
            spa.Options.DefaultPage = "/home/index";
        });
    }

Everything works well except for the fact that images and other static resources are accessed relatively to the initial url instead of the root.

eg When my initial url is https://localhost:44380/, images are correctly fetched from https://localhost:44380/.

enter image description here

However when my initial url is https://localhost:44380/administration/user-profiles, images are incorrectly fetch from: https://localhost:44380/administration/. enter image description here

I am not able to change the css as its a 3rd party library. Hence I would like to just route all resource files to the root url.

Edit: Here is the css of that "x"

.chosen-container-multi .chosen-choices .search-choice .search-choice-close {
    background: url("chosen-sprite.png") right top no-repeat;
    display: block;
    font-size: 1px;
    height: 10px;
    position: absolute;
    right: 4px;
    top: 5px;
    width: 12px;
    cursor: pointer; }

Solution

  • Eventually this did the trick

            app.UseHttpsRedirection();  
    
            app.Use((context, next) =>
            {
                if (!string.IsNullOrWhiteSpace(System.IO.Path.GetExtension(context.Request.Path)))
                {
                    context.Request.Path = Invariant($"/{System.IO.Path.GetFileName(context.Request.Path)}");
                }
                return next();
            });
    
            app.UseStaticFiles();