简体   繁体   English

asp.net核心缺少javascript文件路由问题

[英]asp.net core missing javascript files routing issue

I'm facing an issue where any missing .js files are returned as a 200 ok result from the server and the content of the file is the markup of the _Layout.cshtml file.我面临一个问题,任何丢失的 .js 文件都作为 200 ok 结果从服务器返回,并且文件的内容是 _Layout.cshtml 文件的标记。 It makes sense since I'm using a catch-all route (we're developing a single page app) with a default action:这是有道理的,因为我使用的是带有默认操作的全能路由(我们正在开发单页应用程序):

app.UseMvc(routes =>
{
    routes.MapRoute("default", "{controller=App}/{action=Index}");

    routes.MapRoute(
        name: "single-page",
        template: "{*url}",
        defaults: new {controller = "App", action = "Index"});
    });
}

So if I add a reference to the _Layout.cshtml for a file which doesn't exist, like this:因此,如果我为不存在的文件添加对 _Layout.cshtml 的引用,如下所示:

<script src="~/js/thisDoesntExist.js"></script>

I get the following result from the server:我从服务器得到以下结果:

在此处输入图片说明

Is there any way to tell my routing that if the physical file doesn't exist, then return a 404?有什么方法可以告诉我的路由,如果物理文件不存在,则返回 404? :-) :-)

Thanks in advance.提前致谢。

That is literally what catch-all means.从字面上看,这就是包罗万象的意思。 It's going to catch every single thing and route it to AppController.Index , so everything is going to be a 200. No, there's nothing you can do about that.它会捕获每件事并将其路由到AppController.Index ,所以一切都将是 200。不,你对此无能为力。 I mean, you could manually check if the URL maps to a physical file, and alternatively either manually return a 404 (if it doesn't exist) or a the file itself, but then you're taking over static file handling, which is going to be highly inefficient, and require a lot of extra logic to do properly (accounting for cache control, etc.).我的意思是,您可以手动检查 URL 是否映射到物理文件,或者手动返回 404(如果它不存在)或文件本身,但随后您将接管静态文件处理,即将非常低效,并且需要大量额外的逻辑才能正确执行(考虑缓存控制等)。

You don't need a catch-all route just because you have a SPA.您不需要仅仅因为拥有 SPA 就需要一条万能路线。 In fact, it would be better if you didn't, so all the static resources the SPA is going to rely on can be served more efficiently, and you can actually have things like API endpoints.事实上,如果您不这样做会更好,这样 SPA 将依赖的所有静态资源都可以更有效地提供服务,并且您实际上可以拥有 API 端点之类的东西。 As it is, there's not even a point to this being an ASP.NET Core application.事实上,这是一个 ASP.NET Core 应用程序甚至没有任何意义。 You might as well just do a pure static site with an index.html.你也可以只做一个带有 index.html 的纯静态站点。

Long and short, get rid of the catch-all route.长短不一,摆脱包罗万象的路线。 Just have the default route be your main app landing page.只需将默认路由设置为您的主应用程序登录页面即可。 That's all you need.这就是你所需要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM