Ste*_*per 6 javascript asp.net-mvc url-routing asp.net-mvc-routing requirejs
我想.js使用ASP.NET MVC 5 自动生成一些JavaScript文件,其URL中有适当的扩展名.
这是我的问题;
我在我的网站上使用require.js并且它运行良好.但是,并非所有JavaScript文件都是磁盘上的真实文件.其中一些必须在运行时生成.所以我编写了一个生成动态JavaScript文件的控制器,并在使用默认路由时为它们提供服务;
// ~/Resource/CommonRes -- from ResourceController.CommonRes()
define([], function() {
return {
"menuItemConfiguration":"Configuration",
"menuItemAdmin":"Admin",
"manageAccount":"Manage Account",
"logOff":"Log off"
...
};
});
Run Code Online (Sandbox Code Playgroud)
但是,我需要将路由作为~/Scripts/Resources/CommonRes.js- .js扩展是至关重要的,因为我实际上正在返回一个require.js模块,要像这样调用;
require(['Resources/CommonRes'], function(commonRes) {
// code the uses the resource file
});
Run Code Online (Sandbox Code Playgroud)
在这种情况下,Resources/CommonRes将始终查找名为的模块~/Scripts/Resources/CommonRes.js.因此需要使用该扩展来提供服务.
我似乎无法使路由正确.我尝试过以下但无济于事;
routes.MapRoute(
name: "Resource Scripts",
url: "Scripts/Resource/{action}",
defaults: new { controller = "Resource" },
namespaces: new string[] { "AITrackRecord.Controllers" }
);
Run Code Online (Sandbox Code Playgroud)
据达林季米特洛夫,
IIS拦截请求,因为它包含文件扩展名并且劫持它认为它是静态文件而不将其传递给您的应用程序.
将此添加到您的Web.config:
<system.webServer>
<handlers>
<add name="ScriptsHandler" path="Scripts/Resource/*.js" verb="GET"
type="System.Web.Handlers.TransferRequestHandler" />
</handlers>
</system.webServer>
Run Code Online (Sandbox Code Playgroud)
然后,路线:
routes.MapRoute(
name: "DynamicJavascript",
url: "Scripts/Resource/{action}.js",
defaults: new { controller = "Resource" }
);
Run Code Online (Sandbox Code Playgroud)
样本控制器:
public class ResourceController : Controller
{
public ActionResult MyScript()
{
return Content("var greeting = \"Hello World!\";");
}
}
Run Code Online (Sandbox Code Playgroud)
结果:

| 归档时间: |
|
| 查看次数: |
1456 次 |
| 最近记录: |