为所有子路由服务静态文件



i构建了一个使用单页固定的MVC核心应用程序。

我为/api/...配置了一些效果很好的路由。此外,我想为某些路线提供静态文件。例如:

  • 对于 /Home/的所有子路由我想接收/Home/index.html
  • 对于 /App/的所有子路由我想接收 /App/index.html

我向Configure()添加了app.UseStaticFiles(),因此我可以访问/Home/index.html,但它不适用于任何其他子路由。

缺少什么?

我将路由系统更改为属性路由。我添加了HomeController

[Route("")]
public class HomeController : Controller
{
    [Route("")]
    public IActionResult Index()
    {
        return View(); // The Home-page
    }
    [Route("Error")]
    public IActionResult Error()
    {
        // show an error page
        return Content(Activity.Current?.Id?.ToString() ?? HttpContext.TraceIdentifier.ToString());
    }
    [Route("{client}/{*tail}")]
    [Produces("text/html")]
    public IActionResult ClientApp(string client, string tail)
    {
        // show a client app
        try
        {
            return new ContentResult()
            {
                Content = System.IO.File.ReadAllText($"./wwwroot/{client}/index.html"),
                ContentType = "text/html"
            };
        }
        catch
        {
            return RedirectToAction("/Error");
        }
    }
}

我的客户端应用程序在其自己的文件夹(client路由零件)内有一个index.html文件,在wwwroot的内部。当请求试图访问/something/... ClientApp的路由与something匹配为客户端APP文件夹名称,并且index.html发送到客户端。没有重定向,URL保持不变。

如果在Startup中添加 AddMvc之前添加 UseStaticFiles ,则静态文件没有问题

app.UseStaticFiles();
app.UseMvc();

asp.net MVC Core 2.0

中测试

最新更新