当应用程序托管在IIS的虚拟目录中时,如何将Request's ApplicationPath传递给requir

How to pass Request's ApplicationPath to Requirejs config.path's baseUrl when the application is hosted in virtual directory on IIS?

本文关键字:Request requir ApplicationPath IIS 应用程序 虚拟      更新时间:2023-09-26

我有问题运行我的asp.net mvc应用程序的需求。下面我试图给出我在应用程序中定义的所有配置的总结,如文件结构,模块路径等。当应用程序作为父网站托管在IIS中,但当托管在虚拟目录中时,无法加载模块时,这种情况很好。

我的web应用程序的文件结构是:
  • Web/
      /
    • 脚本
      • app/(这是我的应用程序的js文件的位置)
        • common.js(所有视图的通用js代码都在这里)
        • navigation.js
        • /
        • 视图
          • 账户/
          • login.js
      • vendor/(这里有所有特定于供应商的js文件)
        • jquery.js
        • domReady.js
      • main.js (requirejs配置文件)

的代码如下:

所有视图使用的主布局文件:

这个脚本引用位于header部分:

<script src="@Url.Content("~/Scripts/Vendor/require.js")"></script>
<script data src="@Url.Content("~/Scripts/main.js")"></script>

main.js -配置文件:如下所示,baseurl是根据main.js配置文件设置的。

require.config({
    baseUrl: "../scripts",
    paths: {
        "common": "app/common",
        "jquery": "vendor/jquery-1.11.0",
        "domReady": "vendor/domReady-2.0.1",
        "sammy": "vendor/sammy-0.7.4",
        "jqueryui": "vendor/jquery-ui-1.10.4.min",
        "jquery.validate": "vendor/jquery.validate",
        "jquery.validate.unobtrusive": "vendor/jquery.validate.unobtrusive",
        "jquery.cookie": "vendor/jquery.cookie",
        "bootstrap": "vendor/bootstrap.min"
    },
    shim: {
        'sammy': ['jquery'],
        "jqueryui": {
            exports: "$",
            deps: ['jquery']
        },
        "jquery.validate": {
            deps: ['jquery']
        },
        "jquery.validate.unobtrusive": {
            deps: ['jquery', 'jquery.validate']
        },
        "jquery.cookie": {
            deps: ['jquery']
        },
        "bootstrap": {
            deps: ['jquery']
        }
    }
});

我试图在自己的单独文件中创建视图特定的js代码。您可以在上面的文件结构中看到这一点,其中login.js用于登录。CSHTML,然后使用主布局文件。为了加载login.js,我在视图中使用这个:

<script>
    require(["@Url.Content("~/Scripts/app/views/account/login.js")"], function() {});
</script>

login.js中的代码如下:这有其登录视图特定的代码,它还加载了common.js文件中编写的代码。

 define(["common"],function ($) {
    // use [data-shell-spinner="generic"] on element to use it as a spinner.
    console.log("login view");
});

根据上面的配置,当这个web应用程序作为父目录托管在本地IIS上时,一切正常。

我无法理解为什么当相同的应用程序托管在本地IIS的虚拟目录中时,我会得到以下错误。我知道这发生在上述登录时。CSHTML呈现:

GET http://localhost: 1045/scripts/app/common.js 404 (Not Found)
Uncaught Error: Script error for: common

此应用程序的所有相同源文件驻留在父应用程序下的vd虚拟目录中。路由,加载应用中使用的其他css, js,图像没有问题。

但是我如何确保我在main.js配置文件中定义的所有路径和加载视图特定文件按预期工作,即使应用程序托管在虚拟目录中?

尝试将此添加到您的主布局页面的<head>:

<base href="@(Request.ApplicationPath == "/" ? "/" : Request.ApplicationPath + "/")">

这应该使所有的脚本加载相对于基本路径,它应该正确地解析到你的虚拟目录(或网站根,如果你不使用虚拟目录)。

你可以在这里阅读更多关于base标签的信息。

使用base标签,如gerrod所建议的,效果很好。但是,它会破坏散列标签锚。相反,我建议直接使用等于应用程序路径的baseUrl配置require。

<script>
    var appPath = @Url.Content("~/");
    require.config({
        baseUrl: appPath
    });
</script>