相对路径上的 .Net Core Spa 资源路由

.Net Core Spa Resource Routing on Relative paths

我配置了以下 .net 核心 spa 应用程序

    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";
        });
    }

除了相对于初始 url 而不是根访问图像和其他静态资源这一事实外,一切都运行良好。

例如当我的初始 url 是 https://localhost:44380/, images are correctly fetched from https://localhost:44380/.

但是当我的初始 url 是 https://localhost:44380/administration/user-profiles, images are incorrectly fetch from: https://localhost:44380/administration/ 时。

我无法将 css 更改为第 3 方库。因此我想将所有资源文件路由到根目录 url.

编辑: 这是 "x"

的 css
.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; }

用~/来指代根目录,换句话说https://localhost:44380

这是浏览器的默认行为

您在 css

上使用了相对路径
background: url("chosen-sprite.png") right top no-repeat;

根据规格:

Partial URLs are interpreted relative to the source of the style sheet, not relative to the document

因此,如果您的样式表是从 https://localhost:44380/administration/ 加载的(您可以在 devtools 网络面板上查看),浏览器将尝试从那里加载图像。

stack overflow question that I found

中有关于此问题的更多信息

最终成功了

        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();