ASP.net核心MVC捕获所有路由服务静态文件 [英] ASP.net core MVC catch all route serve static file

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

问题描述

是否有一种方法可以使所有路由都为静态文件服务?

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核心MVC捕获所有路由服务静态文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆