【问题标题】:Post a model from angularJS to WEBAPI将模型从 angularJS 发布到 WEBAPI
【发布时间】:2016-07-22 05:53:30
【问题描述】:

这可能是一个愚蠢的问题,但我无法正确回答。我已经搜索了所有关于 stackoverflow 的问题,当然还有谷歌。

所以,我在我的 webapi 上得到了这个类

public partial class TaskList
{
    public int id { get; set; }
    public string task { get; set; }
}

然后是我的 webapi 控制器

[HttpPost]
public HttpResponseMessage Post([FromBody] TaskList tasklistModel)
{
    return Request.CreateResponse(HttpStatusCode.OK, tasklistModel);
}

我的 angularJS 控制器

angular.module('ReminderDude.controllers', [])

.controller('HomeController', function($scope, dudeService) {
    $scope.CreateNewTask = function(tasklistModel){
        tasklistModel.id = '1';

        dudeService.store({
            data: JSON.stringify(tasklistModel)
        }).then(function(resp) {
            console.log(resp);
         },function(err) {
            console.error('Controller: Error', err);
        });
    }
})

我的 angularJS 服务

angular.module('ReminderDude.services', [])

.factory('dudeService', function($http) {
    var baseUrl = 'http://localhost:1142/api/values';
    return {
        store: function (tasklistModel){
            return $http({  
                        url: baseUrl,
                        method: 'POST',  
                        data: tasklistModel,  
                        headers: {  
                            "Content-Type": "application/json"  
                        }  
                    });
        }
    };
})

最后,HTML

<ion-view view-title="Reminder Dude">
    <ion-content class="padding">
        <form ng-Submit="CreateNewTask(model)">
            <div class="list card">
                <div class="item item-divider">Hello! Please input your task below</div>
                <div class="item item-input">
                    <input type="text" ng-model="model.task" placeholder="Write Here" />
                </div>
            </div>
            <center>
                <button type="submit" class="button button-positive button-large">Save</button>
            </center>
        </form>
    </ion-content>
</ion-view>

我在我的 webapi 控制器上设置了一个断点,它命中但我传递的模型为空。这是我的 webapi 控制器返回的数据:

Object {data: Object, status: 200, config: Object, statusText: "OK"}
config: Object    
data: Object       
headers: Object    
method: "POST"    
transformRequest: Array[1]
transformResponse : Array[1]
url : "http://localhost:1142/api/values"
__proto__ :
    Object: data
    Object:
        id: 0
        task: null
__proto__ :
    Object
    headers: function(name)
    status: 200
    statusText: "OK"
__proto__ :
    Object

这是我尝试过的列表:

  • 在我的 webapi 控制器上使用或删除 [FromBody] 标签
  • 在将我的数据发送到 webapi 控制器之前,在我的 angularJS 控制器上使用或删除 JSON.stringify
  • 将“public HttpResponseMessage Post”更改为“public TaskList Post”
  • console.log 从我的 angularJS 控制器发送的数据:{"task":"testTask","id":"1"}

为什么它没有正确发送到我的 webapi? 任何答案和帮助将不胜感激。

仅供参考:我认为 CORS 不是问题,我已启用它。因为如果没有启用 CORS,它就不会到达断点,不是吗?如果是CORS相关问题,请指正。

谢谢

更新:

经过与@Mahesh Chand 的长时间讨论,我已成功将数据发送到我的 webapi 控制器。这是我所做的:

将 angularjs 控制器更改为:

angular.module('ReminderDude.controllers', [])

.controller('HomeController', function($scope, dudeService) {   
    $scope.CreateNewTask = function(tasklistModel){
        tasklistModel.id = 1;

        //before
        dudeService.store({
            data: tasklistModel
        }).then(function(resp) {
        console.log('response from api:'))
        console.log(resp);

        //after
        dudeService.store(tasklistModel).then(function(resp) {
            console.log('response from api:');
            console.log(resp);
            //ignore the console.log, it just my code to test the response from the api

非常感谢@Mahesh Chand,感谢您注意到不必要的“数据”。 (这是一个愚蠢的错误)

@Mahesh Chand 的注意事项:就我而言,我们确实需要 ng-model 而不是 ng-bind。如果我使用 ng-bind,我不会得到我从视图中传递的值。

希望这能帮助其他和我有同样问题的人。

【问题讨论】:

    标签: c# angularjs asp.net-mvc-4 asp.net-web-api ionic-framework


    【解决方案1】:

    [FromBody] 仅在发布请求具有表单数据时使用,但在您的情况下,您仅在请求中提交数据。因此,您必须在 API 控制器的 Action 中删除 [FromBody]

     [Route("save"), HttpPost]
     public HttpResponseMessage Post(TaskList tasklistModel)
    

    为了一个好的实践,在 Api Controller 上使用 RoutePrefix 属性,在 Action 上使用 Route 属性,如下所述:

     [RoutePrefix("api/my")]
     public class MyController : ApiController
     {
        [Route("save")]
        [HttpPost]
        public HttpResponseMessage Post(TaskList tasklistModel)
        {
           //Your code here
        }
     }
    

    请求会自动序列化。因此,您必须删除 Json.Stringify。 您应该在控制器中使用模型的 id 作为整数而不是字符/字符串。

    angular.module('ReminderDude.controllers', [])
    .controller('HomeController', function($scope, dudeService) {
        //initialize the model here
        $scope.tasklistModel = {};
        //No need to pass it in parameter since it is directly accessible to View
        $scope.CreateNewTask = function(){
             $scope.tasklistModel.id = 1;
    
            dudeService.store($scope.tasklistModel).then(function(resp) {
                console.log(resp);
             },function(err) {
                console.error('Controller: Error', err);
            });
        }
    })
    

    您的 Angular 服务也需要进行一项更改。您应该使用 $http 中可用的 post 功能,如下所述:

    angular.module('ReminderDude.services', [])
    
    .factory('dudeService', function($http) {
        var baseUrl = 'http://localhost:1142/api/values';
        return {
            store: function (tasklistModel){
                //url will be baseUrl + api controller route prefix + action route
                console.log(tasklistModel)
                return $http.post(baseUrl+'api/my/save',tasklistModel);
            }
        };
    })
    

    试试 ng-bind,你的 HTML 会是

    <ion-view view-title="Reminder Dude">
        <ion-content class="padding">
            <form ng-Submit="CreateNewTask()">
                <div class="list card">
                    <div class="item item-divider">Hello! Please input your task below</div>
                    <div class="item item-input">
                        <input type="text" ng-bind="tasklistModel.task" placeholder="Write Here" />
                    </div>
                </div>
                <center>
                    <button type="submit" class="button button-positive button-large">Save</button>
                </center>
            </form>
        </ion-content>
    </ion-view>
    

    【讨论】:

    • 嘿,感谢您的回答,我已经完成了您推荐的更改。但在 [HttpPost] 属性之前添加 [Route("save")] 后,它给了我一个错误 405 (Method Not Allowed)
    • @William 我已经通过控制器和 HTML 的更多更改更新了我的答案。一个问题,您的 api 控制器操作是否被调用?
    • 完整的 URL 将是域名 + 控制器的 RoutePrefix + 操作路径,即localhost:1142/api/my/save 我的答案
    • 被调用是什么意思?如果通过给出断点并且当我调用它时它会命中,那么是的。
    • web api的action中参数还是null吗?
    猜你喜欢
    • 2021-03-24
    • 2015-11-28
    • 2013-01-17
    • 2017-01-10
    • 2018-02-06
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多