为所有子路由提供静态文件

时间:2017-09-19 19:57:56

标签: asp.net-core-mvc

我使用单页客户端构建MVC Core应用程序。

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

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

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

缺少什么?

1 个答案:

答案 0 :(得分:1)

我将路由系统更改为属性路由。其中我添加了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");
        }
    }
}

我的客户端应用在index.html内的自己的文件夹(client路由部分)中有一个wwwroot文件。当请求尝试访问/something/... ClientApp的路由与something匹配作为client-app文件夹名称并且index.html被发送到客户端时。没有重定向,网址保持不变。

如果您在UseStaticFilesAddMvc之前添加Startup ,则不会导致静态文件出现问题:

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

ASP.NET MVC Core 2.0 中测试。