【问题标题】:Using Razor Inside of Javascript to Alter AngularJS "$http.post" URL在 Javascript 中使用 Razor 更改 AngularJS “$http.post” URL
【发布时间】:2019-12-02 15:11:06
【问题描述】:

我正在使用 C# ASP.NET,并使用 AngularJS 构建了一些 Web API、cshtml 和 Javascript 文件。

特别是在 Javascript 文件中,AngularJS $http.post() 方法运行良好,但是,当我将 ASP.NET 网站发布到具有以下 URL 的 IIS 中的 Web 服务器时,问题就出现了: https://website.com/Staging/xxx - http post 方法试图到达 https://website.com/API/xxx 而不是 https://website.com/Staging/API/xxx - 我该如何克服这个问题?

我尝试将一些 Razor 语法偷偷带入 Javascript 文件,但 Visual Studio IDE 就是不接受它。这是我的 $http.post 方法:

$http.post('../api/RefreshLevel/', parameters ).then(function(response)

无论 IIS 应用程序的主目录是在 https://website.com/ 还是 https://website.com/Staging 中运行,我如何更改此 url 使其能够访问 API

希望这是有道理的。

【问题讨论】:

  • 我在 JavaScript 中没有看到任何 Razor 语法,但是如果您将 Razor 添加到 JavaScript 文件,那么您必须通过 Razor 引擎传递这些文件,这通常不会发生(永远原因)。我建议将data- 属性添加到您可以在页面加载后获取的htmlbody 元素,或者添加一个API 方法来返回您可以在需要时调用的信息。

标签: angularjs razor


【解决方案1】:

如果您的 AngularJS 应用程序的路由是这样的:https://website.com/Staging/#!/your-angularjs-routing

你可以使用:

var path = window.location.origin + window.location.pathname

var path = window.location.href.split("#")[0]

变量“路径”将具有“https://website.com/Staging/”。现在你可以做

$http.post(path + 'api/RefreshLevel/', parameters ).then(function(response)

这会给你https://website.com/Staging/api/RefreshLevel/

【讨论】:

    猜你喜欢
    • 2011-10-25
    • 1970-01-01
    • 1970-01-01
    • 2014-05-26
    • 1970-01-01
    • 2022-06-18
    • 2016-02-23
    • 2012-11-08
    • 2013-06-06
    相关资源
    最近更新 更多