【问题标题】:Pass JSON object to WebApi将 JSON 对象传递给 WebApi
【发布时间】:2016-04-01 05:50:25
【问题描述】:

我正在尝试将数据从我的网页发布到我的 RegistrationController Api。我在提交表单时看到了它,但是当我在 WebApi 上命中断点时,参数“pilot”为空。有人能告诉我我需要做什么才能将数据从网页传递到 Registration ApiController 吗?

我看到了这个post,但它似乎对我不起作用。这个post,接近我的问题,提到模型需要注释,但仍然不适合我。

cshtml页面上的按钮:

<button id="submitRegistration" class="btn btn-lg btn-primary btn-block"  
    type="submit">Submit</button>

角度注册控制器:

<script type="text/javascript">
'use strict';

var sampleApp = angular.module('RegistrationApp', []);

sampleApp.controller('RegistrationController', function ($scope, $http) {
    var registrationData = {
        "firstname": $scope.firstname,
        "lastname": $scope.lastname,
        "faaNumber": $scope.faaNumber
    };

    $('#submitRegistration').click(function () {

        registrationData = {
            FirstName: $scope.firstname,
            LastName: $scope.lastname,
            FAANumber: $scope.faaNumber
        };

       // When I hit this debugger, the data is good.
       debugger;
        $.post("api/registration",
                JSON.stringify(registrationData),
                function (value) {
                $('#registrationMessage').append(value);
                },
                "json"
        );
    });
});
</script>

WebApi RegistrationController 类:

public class RegistrationController : ApiController
{
// *********** Pilot is null when the breakpoint hits here ************
public HttpResponseMessage Post([FromBody]PilotModel pilot)     
{
    this.RegisterPilot(pilot);

    var response = Request.CreateResponse<PilotModel>(HttpStatusCode.Created, pilot);

    return response;
}

private string RegisterPilot(PilotModel pilot)
{
    var result = string.Empty;

    ...

    return result;
}
}

试点模型:

[DataContract]
public class PilotModel
{
    [DataMember]
    public string FirstName { get; set; }

    [DataMember]
    public string LastName { get; set; }

    [DataMember]
    public string FAANumber { get; set; }
}

【问题讨论】:

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


    【解决方案1】:

    由于您想通过 Angular 代码发布数据,因此您应该使用 $http 服务,该服务将根据需要设置正确的内容类型。看起来您已经将 $http 服务注入到您的控制器中。

    var model = { FirstName: "Shyju",
                  LastName: "Happy"
                  FAANumber: "3454353"  };
    
    $.http("api/registration",model)
      .then(function(response) {
          var result=response.data;
          console.log(result);
      }, function(response) {
          //error happened. Inform the user
      });
    

    理想情况下,您应该将 http 调用移至数据服务并将该数据服务注入您的角度控制器。

    如果您仍然想使用 jQuery ajax(我不推荐),您可以将您的对象转换为 json 字符串并将contentType 属性指定为"application/json"。即使您的模型具有复杂的导航属性,这种方法也可以工作。

    $.ajax({
            type: "POST",
            data :JSON.stringify(model),
            url: "api/registration",
            contentType: "application/json"
        });
    

    看看this answer,它几乎涵盖了使用 ajax 向 web api 发送数据的所有用例。

    【讨论】:

    • 是的,Angular 已经让 API 调用变得简单了。无需通过 jQuery 来完成。
    • 请注意,并非所有您可能认为实际上由 $http 设置的标头实际上都已设置。最好查看 chrome 工具或其他工具中的默认标题。新的 Asp.Net 5 框架在处理 AJAX 和重定向方面存在一些问题。
    • @shyju,感谢您的回复。我根据您的建议进行了更改,效果很好。我还将研究将 http 调用移动到数据服务中。在我尝试学习这一点时,一次只做一点点。
    【解决方案2】:

    只需一分钟,试一试:

    $.post("api/registration",
                    registrationData,
                    function (value) {
                    $('#registrationMessage').append(value);
                    },
                    "json"
            );
    

    【讨论】:

    • 删除 JSON.stringify() 做到了。我以为我需要那个。我还看到我也没有 DataContract 或 DataMember 属性。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-12
    • 2021-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多