【问题标题】:ASP MVC Angular JS $http not foundASP MVC Angular JS $http 未找到
【发布时间】:2016-04-08 14:39:16
【问题描述】:

我在从我的角度代码调用 http get 到 WebApi 控制器时遇到问题。我使用 ASP MVC 只是为了提供起始页,起始页 url 看起来像:http://localhost:23845/StudentsEditor/StudentsView 现在从角度我调用 http 请求:

angular.element(document).ready(function () {
        $http({
            method: "GET",
            url: "api/Groups/GetGroups",
            dataType: "json",
        }).then(function successCallback(response) {
            $scope.groups = response.data;
        }, function errorCallback(response) {
            alert("trouble...");
        });

我收到 404,因为 URL 不正确。它连接路径,它看起来像: 获取http://localhost:23845/StudentsEditor/api/Groups/GetGroups 而不是http://localhost:23845/api/Groups/GetGroups

请给我一些建议来解决它。当然我已经定义了RouteConfig: 公共静态无效注册路由(RouteCollection 路由) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "StudentsEditor", action = "StudentsView", id = UrlParameter.Optional }
    );

和 webApi 配置:

        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "{url}/api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        var json = config.Formatters.JsonFormatter;
        json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
        config.Formatters.Remove(config.Formatters.XmlFormatter);

【问题讨论】:

    标签: angularjs asp.net-mvc http http-status-code-404


    【解决方案1】:

    你不应该这样硬编码网址。您可以在 Razor 视图中使用 Url.Content 或 Url.RouteUrl 辅助方法来生成应用程序基础/根目录的相对 url。无论您当前的页面/路径如何,它都会正确构建 url。获得此值后,您可以使用 Angular 的 value 提供程序将此数据从您的剃刀视图传递到您的角度控制器/角度数据服务。

    所以在你的剃刀视图(特定页面/布局文件)中,你可以添加这个。

    <script>
        var myApp = myApp || {};
        myApp.Urls = myApp.Urls || {};
        myApp.Urls.baseUrl = '@Url.Content("~")';       
    </script>
    <script src="~/Scripts/AngularControllerForPage.js"></script>
    <script>
        var a = angular.module("app").value("appSettings", myApp);
    </script>
    

    在您的角度控制器中,appSettings 将被注入,您可以使用它并为您的其他 web api 端点构建正确的 url。

    var app = angular.module("app", []);
    var ctrl = function (appSettings,$http) {
    
        var vm = this;
    
        vm.baseUrl = appSettings.Urls.baseUrl;
        //build other urls using the base url now
        var getUGroupsUrl = vm.baseUrl + "api/Groups/GetGroups";
        // you can use getUGroupsUrl  now for your http calls.
        console.log(getUGroupsUrl);
    
       $http.get(getUGroupsUrl).then(function(response) {
    
           console.log(response.data);
       }
    
    };
    ctrl.inject=['$http'];
    app.controller("ctrl", ctrl)
    

    您也可以考虑将 Web api 调用从 angular 控制器转移到 a data service 以保持清洁并保持关注点分开。

    【讨论】:

      【解决方案2】:

      我找到了完成我所寻找的简单方法:

       angular.element(document).ready(function () {
              $http({
                  method: "GET",
                  url: window.location.origin + '/api/Groups/GetGroups',
                  dataType: "json",
              }).then(function successCallback(response) {
                  $scope.groups = response.data;
              }, function errorCallback(response) {
                  alert("trouble..");
              });
          });
      

      关键是window.location.origin,它返回协议+主机+端口

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-16
        • 1970-01-01
        • 1970-01-01
        • 2014-09-09
        • 1970-01-01
        • 2019-07-10
        • 2017-12-23
        • 2014-06-16
        相关资源
        最近更新 更多