Asp.Net MVC 4 clean URL 从子目录加载 index.html

Asp.Net MVC 4 clean URL load index.html from subdirectory

我有一个 ASP.NET MVC 4 项目,我在根目录中有一个子目录 "test",它包含一个 index.html

我想要干净的 URL 被调用 index.html 被返回

当我打电话给

http://localhost:8080/

我收到了从我的 "test\index.html"

返回的内容

调整App_Start子目录下的RouteConfigclass,使Controller默认为Test。将您的 'test' 目录放在 Views 目录中,如果您还没有,请创建一个 TestControllerRouteConfig 应该是这样的:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Test", action = "Index", id = UrlParameter.Optional }
        );
    }
}

最简单的方法是将您的 "test/index.html" 作为 IIS 中的默认文档。

如果您真的想以编程方式执行此操作,则必须创建一个操作来处​​理您的请求并将您的默认路由映射到它。

路线:

routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "StaticFile", action = "Index", id = UrlParameter.Optional }
        );

Controller/Action:

public class StaticFileController : Controller
{
    // GET: StaticFile
    [AllowAnonymous]
    public FileContentResult Index()
    {
        string imageFile = System.Web.HttpContext.Current.Server.MapPath("~/Test/Index.html");
        byte[] bytes = System.IO.File.ReadAllBytes(imageFile);

        return File(bytes, "text/html");
    }
}