gpt4 book ai didi

asp.net-mvc - 如何设置 MVC 可移植区域以使用复杂目录结构中的资源?

转载 作者:行者123 更新时间:2023-12-02 01:22:08 25 4
gpt4 key购买 nike

我在 MVC 2 应用程序中使用可移植区域。我的文件夹中有一个 javascript 文件/Scripts/ViewModels/ViewModel.js 但当我尝试访问它时,出现 404 错误,表示未找到。可移植区域的注册如下所示:

private void RegisterRoutes(AreaRegistrationContext context)
{
context.MapRoute(
AreaName + "_resources",
base.AreaRoutePrefix + "/resource/{resourceName}",
new { controller = "EmbeddedResource", action = "Index"},
new[] { "MvcContrib.PortableAreas" }
);

context.MapRoute(
AreaName + "_scripts",
base.AreaRoutePrefix + "/Scripts/{resourceName}",
new { controller = "EmbeddedResource", action = "Index", resourcePath = "scripts" },
new[] { "MvcContrib.PortableAreas" }
);

context.MapRoute(
AreaName + "_images",
base.AreaRoutePrefix + "/images/{resourceName}",
new { controller = "EmbeddedResource", action = "Index", resourcePath = "images" },
new[] { "MvcContrib.PortableAreas" }
);

context.MapRoute(
AreaName + "_default",
base.AreaRoutePrefix + "/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
new[] { "PortableAreaDemo.PortableAreas.Areas.Demo.Controllers", "MvcContrib" }
);
}

在 View 模板中,我尝试包含脚本文件 <script src="@Url.Content("~/Demo/Scripts/ViewModels/ViewModel.js")"></script>我得到以下网址 /Demo/Scripts/ViewModels/ViewModel.js但该文件无法访问。我只能访问 Scripts 文件夹的直接子级脚本文件。

最佳答案

来自 MSDN Documentation关于路由,

Sometimes you have to handle URL requests that contain a variable number of URL segments. When you define a route, you can specify that if a URL has more segments than there are in the pattern, the extra segments are considered to be part of the last segment. To handle additional segments in this manner you mark the last parameter with an asterisk (*). This is referred to as a catch-all parameter. A route with a catch-all parameter will also match URLs that do not contain any values for the last parameter.

因此,您应该尝试将 * 添加到脚本路径参数的开头,例如 base.AreaRoutePrefix + "/Scripts/{*resourceName}", 这将允许参数作为一个包罗万象的处理。然后,resourceName 将能够分配给 /ViewModel.js/ViewModels/ViewModel.js。如果没有 */ViewModels 段将被视为另一个段,这会导致路由引擎不会将此路由评估为匹配项,而是继续执行已定义的路由,并且404 是没有与所提供的 URL 路径模式匹配的路由的结果。

关于asp.net-mvc - 如何设置 MVC 可移植区域以使用复杂目录结构中的资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19144541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com