创建MVC路由结束“.js”并返回JavaScript? [英] Create a MVC route ending ".js" and returning JavaScript?

查看:77
本文介绍了创建MVC路由结束“.js”并返回JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用ASP.NET MVC 5自动生成一些JavaScript文件,其URL中有正确的 .js 扩展名。

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

这是我的问题;

我正在使用 require.js 遍布我的网站并且运行良好。但是,并非所有JavaScript文件都是磁盘上的真实文件。其中一些必须在运行时生成。所以我编写了一个生成动态JavaScript文件的控制器,并在使用默认路由时为它们提供服务;

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" 
        ...
    };
});

但是,我需要将路由作为〜/ Scripts / Resources /CommonRes.js - .js 扩展名是至关重要的,因为我实际上正在返回 require.js 模块,可以像这样调用;

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
});

在这种情况下,模块名为 Resources / CommonRes 将始终在〜/ Scripts / Resources / CommonRes.js 中查找。因此需要使用该扩展来提供它。

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" }
);


推荐答案

根据Darin Dimitrov


IIS拦截请求,因为它包含一个文件扩展名并且劫持它认为它是一个静态文件并且没有将它传递给你的应用程序。

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.

将此添加到 Web.config

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

然后,路线:

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

样本总监:

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

结果:

这篇关于创建MVC路由结束“.js”并返回JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆