ASP.net core MVC 捕获所有路由服务静态文件

0

本文介绍了ASP.net core MVC 捕获所有路由服务静态文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

有没有办法让 catch all 路由服务于静态文件?

Is there a way to make a catch all route serve a static file?

看这个http://blog.nbellocam.me/2016/03/21/routing-angular-2-asp-net-core/

我基本上想要这样的东西:

I basically want something like this:

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

            routes.MapRoute("spa", "{*url}"); // This should serve SPA index.html
        });

所以任何与 MVC 控制器不匹配的路由都会提供 wwwroot/index.html

So any route that doesn't match an MVC controller will serve up wwwroot/index.html

推荐答案

如果您已经处于路由阶段,那么您已经过了在管道中提供静态文件的阶段.您的初创公司将如下所示:

If you're already in the routing stage, you've gone past the point where static files are served in the pipeline. Your startup will look something like this:

app.UseStaticFiles();

...

app.UseMvc(...);

这里的顺序很重要.因此,您的应用将首先查找静态文件,这从性能的角度来看是有意义的 - 如果您只想丢弃静态文件,则无需运行 MVC 管道.

The order here is important. So your app will look for static files first, which makes sense from a performance standpoint - no need to run through MVC pipeline if you just want to throw out a static file.

您可以创建一个包罗万象的控制器操作,该操作将返回文件的内容.例如(窃取您评论中的代码):

You can create a catch-all controller action that will return the content of the file instead. For example (stealing the code in your comment):

public IActionResult Spa()
{
    return File("~/index.html", "text/html");
}

这篇关于ASP.net core MVC 捕获所有路由服务静态文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14