【问题标题】:What is a robust way of getting urls for use in AngularJS http from mvc.net?什么是从 mvc.net 获取用于 AngularJS http 的 URL 的可靠方法?
【发布时间】:2014-09-20 13:53:06
【问题描述】:

在 Angular 中使用 http 时,必须在 JavaScript 中指定 url。我不想对完整的 url 进行硬编码(例如 http://www.example.com/Controller/GetDetails/),因为这将意味着实时环境和测试环境之间的代码更改。

我已经阅读了仅使用相对路径的示例(例如 /Contoller/GetDetails),但是由于 MVC 路由的工作方式,这通常无法正常工作。作为一个简单的示例,可以通过以下方式访问主页:

  1. http://www.example.com
  2. http://www.example.com/home/
  3. http://www.example.com/home/index

因此添加相对路径并不理想,因为这些路由中有三分之二会得到错误的 http url。

我最初认为我可以从 JavaScript 中确定基本 url 并使用:

window.location.protocol+"//"+window.location.host + "/Contoller/GetDetails"

但我发现如果 MVC 应用程序在文件夹中运行并且无法正确解析如下网址,则此操作会失败:

http://www.example.com/MyApplication/Controller/GetDetails

我还考虑使用更 RESTful 的方法并将 JavaScript 所需的所有 url 作为 json 数据的一部分交给 - 但当然,这会导致先有鸡还是先有蛋的情况:如果 http url 在json,如何让第一个 json 调用工作?

获取用于 AngularJS http 调用 mvc.net 的 url 的可靠方法是什么?

【问题讨论】:

    标签: javascript asp.net-mvc json angularjs


    【解决方案1】:

    如果您使用 angular - 您需要查看 window 服务 - $windowlocation 服务 - @ 987654322@。使用这些,您将轻松解决相对路径问题。 此外 - 你所说的 MVC 应用程序文件夹 - 是应用程序上下文。

    【讨论】:

      【解决方案2】:

      这样做的一种方法似乎是使用 .net 代码在布局页面中设置一个 JavaScript 变量,如下所示:

      How to get base URL of an MVC application using javascript

      window.applicationBaseUrl = @Html.Raw(HttpUtility.JavaScriptStringEncode(
          new Uri(
                     new Uri(this.Context.Request.Url.GetLeftPart(UriPartial.Authority)),
                     Url.Content("~/")
                 ).ToString(), true));
      

      这允许您使用 applicationBaseUrl 调用 http

       $http({
                      method: 'GET', url: window.applicationBaseUrl + '/Controller/GetDetails'
                  })
      

      【讨论】:

      • 很好,除了你应该用 Angular 常量替换 window.applicationBaseUrl 以实现依赖注入和可测试性:yourApp.constant('applicationBaseUrl', @Html.Raw(HttpUtility.JavaScriptStringEncode(Url.Content("~/"), true)));
      猜你喜欢
      • 1970-01-01
      • 2018-03-19
      • 1970-01-01
      • 2016-07-31
      • 2017-03-01
      • 2021-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多