Create an MVC route ending with ".js" and returning JavaScript?

I would like to auto-generate some JavaScript files with the corresponding .js extensions in my URLs using ASP.NET MVC 5.

Here is my problem;

I use require.js on my website and it works very well. However, not all of my JavaScript files are real files on disk. Some of them must be created at runtime. Therefore, I wrote a controller that generates dynamic JavaScript files and serves them when using default routing;

 // ~/Resource/CommonRes -- from ResourceController.CommonRes() define([], function() { return { "menuItemConfiguration":"Configuration", "menuItemAdmin":"Admin", "manageAccount":"Manage Account", "logOff":"Log off" ... }; }); 

However, I need the route to be accessible as ~/Scripts/Resources/CommonRes.js - the .js extension is vital since I actually return require.js , which will be called like this:

 require(['Resources/CommonRes'], function(commonRes) { // code the uses the resource file }); 

And in this case, a module named Resources/CommonRes will always look in ~/Scripts/Resources/CommonRes.js . Therefore, you must service it with this extension.

I cannot configure routing correctly. I tried the following, but to no avail;

 routes.MapRoute( name: "Resource Scripts", url: "Scripts/Resource/{action}", defaults: new { controller = "Resource" }, namespaces: new string[] { "AITrackRecord.Controllers" } ); 
+6
source share
1 answer

According to Darin Dimitrov ,

IIS intercepts the request because it contains the file extension and captures it, thinking it is a static file and does not transfer it to your application.

Add this to your Web.config :

 <system.webServer> <handlers> <add name="ScriptsHandler" path="Scripts/Resource/*.js" verb="GET" type="System.Web.Handlers.TransferRequestHandler" /> </handlers> </system.webServer> 

Then the route:

 routes.MapRoute( name: "DynamicJavascript", url: "Scripts/Resource/{action}.js", defaults: new { controller = "Resource" } ); 

Sample Controller:

 public class ResourceController : Controller { public ActionResult MyScript() { return Content("var greeting = \"Hello World!\";"); } } 

Result:

Result

+8
source

Source: https://habr.com/ru/post/975684/


All Articles