Create a MVC route ending “.js” and returning Java

2020-07-10 08:34发布

问题:

I'd like to auto-generate some JavaScript files, with proper .js extensions in their URLs, using ASP.NET MVC 5.

Here's my problem;

I'm using require.js throughout my site and it's working pretty well. However, not all of my JavaScript files are real files on disk. Some of them must be generated at runtime. So I've written a controller which generates the dynamic JavaScript files, and serves them when using the default routing;

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

However, I need to have the route available as ~/Scripts/Resources/CommonRes.js -- the .js extension is vital since I'm actually returning a require.js module, to be invoked like this;

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

And in this case, the module named Resources/CommonRes will always be looked for at ~/Scripts/Resources/CommonRes.js. Hence the need to serve it up with that extension.

I can't seem to get the routing correct. I've 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" }
);

回答1:

According to Darin Dimitrov,

IIS intercepts the request because it contains a file extension and hijacks it thinking it is a static file and not passing 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: