【问题标题】:Controller for Web API, RESTful Web Methods. (With Angular)Web API 控制器,RESTful Web 方法。 (带角度)
【发布时间】:2020-01-21 20:15:28
【问题描述】:

我对 C# 还很陌生,我完全不知道接下来应该做什么来处理我用 Bootstrap 和 Html 以及 AngularJS 控制器创建的输入表单中的用户输入。

每次我尝试使用我的 api 的 Get 方法返回值时,我的整个控制器都会中断。

我已经阅读了很多关于 RESTful api web 方法的教程和诀窍,我开始对它感到困惑和过度思考,因为我知道这是一个简单的过程。

下面是我的控制器的代码:

public class FeedbackController : ApiController
    {
        // GET: api/Feedback
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET: api/Feedback/
        public string (Feedback id);
        {

        }

        // POST: api/Feedback
        public void Post([FromBody]Feedback value)
        {

        }

        // PUT: api/Feedback
        public void Put( [FromBody]Feedback value)
        {
            var test = value.FeedbackRating;
        }

        // DELETE: api/Feedback/
        public void Delete(Feedback id)
        {
        }
        public string post([FromUri]Feedback value)
        {
            return "Put returning:  " + value;
        }

//angular js
       commonModule.controller('feedbackController', ['$scope', '$modal',                    '       $timeout', 'authenticationService',
         function ($scope, $modal, $timeout, authenticationService) {

      var init = function () {
          $scope.feedbackPopup();
      }

      $scope.feedbackPopup = function () {

          var modalInstance = $modal.open({
              templateUrl: '/Scripts/app/common/views/popup.tpl.html',
              resolve: {

              },
              controller: function ($scope, $modalInstance) {

                  $scope.close = function () {
                      $modalInstance.close();
                  };

                  $scope.submitFeedback = function () {
                      $scope.feedback = {

                         FeedbackRating: 1,
                          FeedbackSubject: 1,
                          FeedbackUpload: 1,
                          FeedbackDescription:1

                      };

                      authenticationService.submitFeedback($scope.feedback).then(
                      // Success Handler
                       function (result) {
                            $modalInstance.close();
                            $scope.message = "Feedback submitted";
                            $timeout(function () {
                                $scope.message = "";
                            }, 3000);
                      },
                      // Failure Handler
                      function () {
                            $scope.message = "Error updating specialization";
                      });
                  }
              }
          });
      }

      init();

       }]);
   })();


Feedback class

{
   public class Feedback
   {
    public int FeedbackRating { get; set; }
    private string EncryptedHexPuid { get; set; }
    public string FeedbackDescription { get; set; }
    public string FeedbackSubject { get; set; }
    }
}

【问题讨论】:

  • 你能发布你的 Angular 控制器代码吗?特别是您的$http 电话,但最好更多
  • 当您说every time I try to return values with my Get methods for my api, my whole controller breaks. 时,您的意思是您的 angular.js 控制器正在进行 $http 调用还是您的 wep api 控制器正在处理请求?
  • 当您在浏览器中点击您的 api URL 时,您会得到预期的响应吗?
  • 我将发布我的 Angular 控制器。
  • 还有 sgwatstack,我的意思是代码不再运行并且帖子中断。意味着存在代码问题。出现的问题是预期的类、委托、枚举、接口或结构。'

标签: c# angularjs rest asp.net-web-api


【解决方案1】:

以下是使用 Angular.js 和 Asp.Net Web Api 设置应用程序的重要部分

index.html

<!doctype html>
<html class="no-js" lang="" ng-app="demo">
<head>
    <meta charset="utf-8">
    <base href="/">
</head>
<body ng-controller="MainController as vm'>
    <h1>Demo</h1>
    <div>{{vm.value[0]}}</div>
    <div>{{vm.value[1]}}</div>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.js"></script>
    <script src="js/app/app.js"></script>
</body>
</html>

app.js

(function () {
    'use strict';

    var app = angular.module('demo', []);

    app.config(config);

    function config($locationProvider, $routeProvider) {
        $locationProvider.html5Mode(true);
    }

    var controller = angular
        .module('demo')
        .controller('MainController', MainController);

    function MainController($http) {
        var vm = this;
         // Here localhost is where your asp.net web api server is serving from
         // The /api/feedback is the url that the FeedbackController
         // in your asp.net web api project answers requests to
         // It returns a json array of two strings
         $http.get('http://localhost:12312/api/feedback').
            success(function (data, status, headers, config) {
                console.log("Success: " + data);
                vm.values = data;
            }).
            error(function (data, status, headers, config) {
                console.log("Error: " + data);
                vm.error = data;
}());

这里是FeedbackController.cs

public class FeedbackController : ApiController
{
    // GET: api/Feedback
    public IEnumerable<Feedback> Get()
    {
        return new Feedback[] { new Feedback(), new Feedback() };
    }

    // GET: api/Feedback/5
    public Feedback Get(int id)
    {
        return new Feedback();
    }

    // POST: api/Feedback
    public IHttpActionResult Post([FromBody]Feedback value)
    {
        return Ok(value);
    }

    // PUT: api/Feedback/5
    public IHttpActionResult Put(int id, [FromBody]Feedback value)
    {
        return Ok(value);
    }

    // DELETE: api/Feedback/5
    public void Delete(int id)
    {
    }
}

请注意,我正在从 Post 和 Put 方法返回 IHttpActionResults。这些操作会返回更合适的结果代码,但这会让您继续前进。

注意:我测试了这段代码,在 Visual Studio 2013 中使用 asp.net web api 模板构建 web api 应用程序时,它一切正常。

【讨论】:

  • 这在我的代码中正确编译!我认为我的问题是我没有完全理解这些。这对我很有帮助,下次我遇到这种情况时应该采取哪些步骤以避免混淆?
  • @Royalgambino 我会推荐浏览 web api 教程 (asp.net/web-api/overview/getting-started-with-aspnet-web-api)。这本书(apress.com/9781484201107)也帮助我理解了这个框架,来自 MVC 背景。这门 MVA 课程 (microsoftvirtualacademy.com/training-courses/…) 非常擅长涵盖 Web api 中 HTTP 请求/响应的基础知识。只知道 REST 将有助于概念,但对 asp.net 应用程序的语法和执行没有帮助。以上内容将对这些有所帮助。
【解决方案2】:

仅根据您提供的有限信息,这里有一个示例角度服务,它将从您的 asp.net 控制器获取值:

angular.module('MyModule', [])
     .service('feedbackService', ['$http', function($http){
         this.getFeedback = function(){
               return $http.get('/api/Feedback');
      }
}]);

angular.module('MyModule',[])
     .controller('pageCtrl', ['$scope','feedbackService', function(scope, feedbackService){
          $scope.$watch('someObj.someProperty', function(){
               feedbackService.getFeedback()
               .then(function(res){ 
                            // Success 
                     }, 
                     function(err) { 
                           // error 
                     }
               );
          }
}]);

考虑到这是一个 REST Api,您可能希望使用 $resource 而不是 $http,因为它在使用 RESTFul 服务时更直观。更多详情:

https://docs.angularjs.org/api/ngResource/service/$resource

【讨论】:

  • 所以我假设问题出在我的角度方法而不是我的 c# 上?
  • 取决于,当您的 ajax 调用发出时,您是否在服务器端出现异常(检查浏览器开发工具中的网络选项卡是否返回 500/404/etc 的错误状态)。如果您收到 500 错误,则说明您的 asp.net 代码有问题。如果您收到 404,您可能遇到了路由问题,或者您的 Angular 代码中有错误的 URL。如果您没有看到任何请求,请检查 javascript 错误,这表明您的 Angular 代码是问题所在。
猜你喜欢
  • 2017-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多