asp.net-mvc 将特定于视图的 javascript 文件放在 ASP.NET MVC 应用程序中的何处?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/604883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Where to put view-specific javascript files in an ASP.NET MVC application?
提问by Erv Walter
What is the best place (which folder, etc) to put view-specific javascript files in an ASP.NET MVC application?
将特定于视图的 javascript 文件放在 ASP.NET MVC 应用程序中的最佳位置(哪个文件夹等)是什么?
To keep my project organized, I'd really love to be able to put them side-by-side with the view's .aspx files, but I haven't found a good way to reference them when doing that without exposing the ~/Views/Action/ folder structure. Is it really a bad thing to let details of that folder structure leak?
为了让我的项目井井有条,我真的很想将它们与视图的 .aspx 文件并排放置,但我还没有找到在不暴露 ~/Views 的情况下引用它们的好方法/Action/ 文件夹结构。让文件夹结构的细节泄露真的是一件坏事吗?
The alternative is to put them in the ~/Scripts or ~/Content folders, but is a minor irritation because now I have to worry about filename clashes. It's an irritation I can get over, though, if it is "the right thing."
另一种方法是将它们放在 ~/Scripts 或 ~/Content 文件夹中,但这有点刺激,因为现在我不得不担心文件名冲突。不过,如果这是“正确的事情”,我可以克服这种刺激。
回答by davesw
Old question, but I wanted to put my answer incase anyone else comes looking for it.
老问题,但我想把我的答案放在以防其他人来找它。
I too wanted my view specific js/css files under the views folder, and here's how I did it:
我也希望在 views 文件夹下查看特定于我的 js/css 文件,这是我的做法:
In the web.config folder in the root of /Views you need to modify two sections to enable the webserver to serve the files:
在 /Views 根目录下的 web.config 文件夹中,您需要修改两部分以使网络服务器能够提供文件:
<system.web>
<httpHandlers>
<add path="*.js" verb="GET,HEAD" type="System.Web.StaticFileHandler" />
<add path="*.css" verb="GET,HEAD" type="System.Web.StaticFileHandler" />
<add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
</httpHandlers>
<!-- other content here -->
</system.web>
<system.webServer>
<handlers>
<remove name="BlockViewHandler"/>
<add name="JavaScript" path="*.js" verb="GET,HEAD" type="System.Web.StaticFileHandler" />
<add name="CSS" path="*.css" verb="GET,HEAD" type="System.Web.StaticFileHandler" />
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>
<!-- other content here -->
</system.webServer>
Then from your view file you can reference the urls like you expect:
然后从您的视图文件中,您可以像预期的那样引用网址:
@Url.Content("~/Views/<ControllerName>/somefile.css")
This will allow serving of .js and .css files, and will forbid serving of anything else.
这将允许提供 .js 和 .css 文件,并禁止提供任何其他内容。
回答by Kirk Woll
One way of achieving this is to supply your own ActionInvoker. Using the code included below, you can add to your controller's constructor:
实现这一目标的一种方法是提供您自己的ActionInvoker. 使用下面包含的代码,您可以添加到控制器的构造函数中:
ActionInvoker = new JavaScriptActionInvoker();
Now, whenever you place a .jsfile next to your view:
现在,每当您将.js文件放在视图旁边时:


You can access it directly:
您可以直接访问它:
http://yourdomain.com/YourController/Index.js
Below is the source:
下面是源码:
namespace JavaScriptViews {
public class JavaScriptActionDescriptor : ActionDescriptor
{
private string actionName;
private ControllerDescriptor controllerDescriptor;
public JavaScriptActionDescriptor(string actionName, ControllerDescriptor controllerDescriptor)
{
this.actionName = actionName;
this.controllerDescriptor = controllerDescriptor;
}
public override object Execute(ControllerContext controllerContext, IDictionary<string, object> parameters)
{
return new ViewResult();
}
public override ParameterDescriptor[] GetParameters()
{
return new ParameterDescriptor[0];
}
public override string ActionName
{
get { return actionName; }
}
public override ControllerDescriptor ControllerDescriptor
{
get { return controllerDescriptor; }
}
}
public class JavaScriptActionInvoker : ControllerActionInvoker
{
protected override ActionDescriptor FindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, string actionName)
{
var action = base.FindAction(controllerContext, controllerDescriptor, actionName);
if (action != null)
{
return action;
}
if (actionName.EndsWith(".js"))
{
return new JavaScriptActionDescriptor(actionName, controllerDescriptor);
}
else
return null;
}
}
public class JavaScriptView : IView
{
private string fileName;
public JavaScriptView(string fileName)
{
this.fileName = fileName;
}
public void Render(ViewContext viewContext, TextWriter writer)
{
var file = File.ReadAllText(viewContext.HttpContext.Server.MapPath(fileName));
writer.Write(file);
}
}
public class JavaScriptViewEngine : VirtualPathProviderViewEngine
{
public JavaScriptViewEngine()
: this(null)
{
}
public JavaScriptViewEngine(IViewPageActivator viewPageActivator)
: base()
{
AreaViewLocationFormats = new[]
{
"~/Areas/{2}/Views/{1}/{0}.js",
"~/Areas/{2}/Views/Shared/{0}.js"
};
AreaMasterLocationFormats = new[]
{
"~/Areas/{2}/Views/{1}/{0}.js",
"~/Areas/{2}/Views/Shared/{0}.js"
};
AreaPartialViewLocationFormats = new []
{
"~/Areas/{2}/Views/{1}/{0}.js",
"~/Areas/{2}/Views/Shared/{0}.js"
};
ViewLocationFormats = new[]
{
"~/Views/{1}/{0}.js",
"~/Views/Shared/{0}.js"
};
MasterLocationFormats = new[]
{
"~/Views/{1}/{0}.js",
"~/Views/Shared/{0}.js"
};
PartialViewLocationFormats = new[]
{
"~/Views/{1}/{0}.js",
"~/Views/Shared/{0}.js"
};
FileExtensions = new[]
{
"js"
};
}
public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
{
if (viewName.EndsWith(".js"))
viewName = viewName.ChopEnd(".js");
return base.FindView(controllerContext, viewName, masterName, useCache);
}
protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
{
return new JavaScriptView(partialPath);
}
protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
{
return new JavaScriptView(viewPath);
}
}
}
回答by Vadym Nikolaiev
You can invert davesw's suggestion and block only .cshtml
您可以反转 davesw 的建议并仅阻止 .cshtml
<httpHandlers>
<add path="*.cshtml" verb="*" type="System.Web.HttpNotFoundHandler"/>
</httpHandlers>
回答by dh6984
I know this is a rather old topic, but I have a few things I would like to add. I tried davesw's answer but it was throwing a 500 error when trying to load the script files, so I had to add this to the web.config:
我知道这是一个相当古老的话题,但我想补充几点。我尝试了 davesw 的回答,但在尝试加载脚本文件时抛出了 500 错误,因此我不得不将其添加到 web.config 中:
<validation validateIntegratedModeConfiguration="false" />
to system.webServer. Here is what I have, and I was able to get it to work:
到 system.webServer。这是我所拥有的,我能够让它工作:
<system.webServer>
<handlers>
<remove name="BlockViewHandler"/>
<add name="JavaScript" path="*.js" verb="GET,HEAD" type="System.Web.StaticFileHandler" />
<add name="CSS" path="*.css" verb="GET,HEAD" type="System.Web.StaticFileHandler" />
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>
<validation validateIntegratedModeConfiguration="false" />
</system.webServer>
<system.web>
<compilation>
<assemblies>
<add assembly="System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<httpHandlers>
<add path="*.js" verb="GET,HEAD" type="System.Web.StaticFileHandler" />
<add path="*.css" verb="GET,HEAD" type="System.Web.StaticFileHandler" />
<add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
</httpHandlers>
</system.web>
Here is more information on validation: https://www.iis.net/configreference/system.webserver/validation
以下是有关验证的更多信息:https: //www.iis.net/configreference/system.webserver/validation
回答by Peter Isaac
add this code in web.config file inside system.web tag
将此代码添加到 system.web 标签内的 web.config 文件中
<handlers>
<remove name="BlockViewHandler"/>
<add name="JavaScript" path="*.js" verb="GET,HEAD" type="System.Web.StaticFileHandler" />
<add name="CSS" path="*.css" verb="GET,HEAD" type="System.Web.StaticFileHandler" />
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>
回答by Drew
I also wanted to place js files related to a view in the same folder as the view.
我还想将与视图相关的 js 文件放在与视图相同的文件夹中。
I wasn't able to get the other solutions in this thread to work, not that they are broken but I am too new to MVC to get them working.
我无法使该线程中的其他解决方案起作用,并不是因为它们已损坏,而是我对 MVC 太新,无法使它们工作。
Using information given here and several other stacks I came up with a solution that:
使用此处提供的信息和其他几个堆栈,我想出了一个解决方案:
- Allows the javascript file to be placed in the same directory as the view it is associated with.
- Script URL's don't give away the underlying physical site structure
- Script URL's don't have to end with a trailing slash (/)
- Doesn't interfere with static resources, eg: /Scripts/someFile.js still works
- Doesn't require runAllManagedModulesForAllRequests to be enabled.
- 允许将 javascript 文件放置在与其关联的视图相同的目录中。
- 脚本 URL 不会泄露底层物理站点结构
- 脚本 URL 不必以斜杠 (/) 结尾
- 不干扰静态资源,例如:/Scripts/someFile.js 仍然有效
- 不需要启用 runAllManagedModulesForAllRequests。
Note: I am also using HTTP Attribute Routing. It's possible that the route's used in my soultion could be modified to work without enabling this.
注意:我也在使用 HTTP 属性路由。有可能在我的灵魂中使用的路线可以修改为在不启用此功能的情况下工作。
Given the following example directory/file structure:
给定以下示例目录/文件结构:
Controllers
-- Example
-- ExampleController.vb
Views
-- Example
-- Test.vbhtml
-- Test.js
Using the configuration steps given below, combined with the example structure above, the test view URL would be accessed via: /Example/Testand the javascript file would be referenced via: /Example/Scripts/test.js
使用下面给出的配置步骤,结合上面的示例结构,将通过以下方式访问测试视图 URL:/Example/Test并且将通过以下方式引用 javascript 文件:/Example/Scripts/test.js
Step 1 - Enable Attribute Routing:
步骤 1 - 启用属性路由:
Edit your /App_start/RouteConfig.vb file and add routes.MapMvcAttributeRoutes()just above the existing routes.MapRoute:
编辑您的 /App_start/RouteConfig.vb 文件并routes.MapMvcAttributeRoutes()在现有 routes.MapRoute 上方添加:
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.Mvc
Imports System.Web.Routing
Public Module RouteConfig
Public Sub RegisterRoutes(ByVal routes As RouteCollection)
routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
' Enable HTTP atribute routing
routes.MapMvcAttributeRoutes()
routes.MapRoute(
name:="Default",
url:="{controller}/{action}/{id}",
defaults:=New With {.controller = "Home", .action = "Index", .id = UrlParameter.Optional}
)
End Sub
End Module
Step 2 -Configure your site to treat, and process, /{controller}/Scripts/*.js as an MVC path and not a static resource
第 2 步 - 配置您的站点以将 /{controller}/Scripts/*.js 处理和处理为 MVC 路径而不是静态资源
Edit your /Web.config file, adding the following to the system.webServer --> handlers section of the file:
编辑 /Web.config 文件,将以下内容添加到文件的 system.webServer --> handlers 部分:
<add name="ApiURIs-ISAPI-Integrated-4.0" path="*/scripts/*.js" verb="GET" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
Here it is again with context:
这里又是上下文:
<system.webServer>
<modules>
<remove name="TelemetryCorrelationHttpModule"/>
<add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" preCondition="managedHandler"/>
<remove name="ApplicationInsightsWebTracking"/>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler"/>
</modules>
<validation validateIntegratedModeConfiguration="false"/>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
<remove name="OPTIONSVerbHandler"/>
<remove name="TRACEVerbHandler"/>
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0"/>
<add name="ApiURIs-ISAPI-Integrated-4.0" path="*/scripts/*.js" verb="GET" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
Step 3 - Add the following scripts action result to your Controller file
第 3 步 - 将以下脚本操作结果添加到您的控制器文件中
- Be sure to edit the route path to match the {controller} name for the controller, for this example it's: <Route("Example/Scripts/{filename}")>
You will need to copy this into each of your Controller files. If you wanted, there is probably a way to do this as a single, one-time, route configuration somehow.
' /Example/Scripts/*.js <Route("Example/Scripts/{filename}")> Function Scripts(filename As String) As ActionResult ' ControllerName could be hardcoded but doing it this way allows for copy/pasting this code block into other controllers without having to edit Dim ControllerName As String = System.Web.HttpContext.Current.Request.RequestContext.RouteData.Values("controller").ToString() ' the real file path Dim filePath As String = Server.MapPath("~/Views/" & ControllerName & "/" & filename) ' send the file contents back Return Content(System.IO.File.ReadAllText(filePath), "text/javascript") End Function
- 请务必编辑路由路径以匹配控制器的 {controller} 名称,在本示例中为: <Route(" Example/Scripts/{filename}")>
您需要将其复制到每个控制器文件中。如果您愿意,可能有一种方法可以以某种方式将其作为单一的、一次性的路由配置来实现。
' /Example/Scripts/*.js <Route("Example/Scripts/{filename}")> Function Scripts(filename As String) As ActionResult ' ControllerName could be hardcoded but doing it this way allows for copy/pasting this code block into other controllers without having to edit Dim ControllerName As String = System.Web.HttpContext.Current.Request.RequestContext.RouteData.Values("controller").ToString() ' the real file path Dim filePath As String = Server.MapPath("~/Views/" & ControllerName & "/" & filename) ' send the file contents back Return Content(System.IO.File.ReadAllText(filePath), "text/javascript") End Function
For context, this is my ExampleController.vb file:
对于上下文,这是我的 ExampleController.vb 文件:
Imports System.Web.Mvc
Namespace myAppName
Public Class ExampleController
Inherits Controller
' /Example/Test
Function Test() As ActionResult
Return View()
End Function
' /Example/Scripts/*.js
<Route("Example/Scripts/{filename}")>
Function Scripts(filename As String) As ActionResult
' ControllerName could be hardcoded but doing it this way allows for copy/pasting this code block into other controllers without having to edit
Dim ControllerName As String = System.Web.HttpContext.Current.Request.RequestContext.RouteData.Values("controller").ToString()
' the real file path
Dim filePath As String = Server.MapPath("~/Views/" & ControllerName & "/" & filename)
' send the file contents back
Return Content(System.IO.File.ReadAllText(filePath), "text/javascript")
End Function
End Class
End Namespace
Final NotesThere is nothing special about the test.vbhtml view / test.js javascript files and are not shown here.
最后说明test.vbhtml 视图/test.js javascript 文件没有什么特别之处,这里没有显示。
I keep my CSS in the view file but you could easily add to this solution so that you can reference your CSS files in a similar way.
我将我的 CSS 保留在视图文件中,但您可以轻松添加到此解决方案中,以便您可以以类似的方式引用您的 CSS 文件。

