将复合类型从JS发送到WCF REST服务

本文关键字:WCF REST 服务 复合 类型 JS | 更新日期: 2023-09-27 18:10:42

以下是代码片段:

1。复杂对象:

[DataContract]
public class NewUser
{
    [DataMember(Name = "Email")]
    public string Email { get; set; }
    [DataMember(Name = "FirstName")]
    public string FirstName { get; set; }
    [DataMember(Name = "LastName")]
    public string LastName { get; set; }
    [DataMember(Name = "Mobile")]
    public string Mobile { get; set; }
    [DataMember(Name = "UserAddress")]
    public Address UserAddress { get; set; }
}

2。操作合同

[OperationContract]
[WebInvoke(UriTemplate = "/RegisterUser", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, Method = "POST")]
Guid Register(NewUser col);

3。JS/Angular的http post调用

var newUser = {};
newUser.Email = $scope.col.Email;
newUser.FirstName = $scope.col.FirstName;
newUser.LastName = $scope.col.LastName;
newUser.Mobile = $scope.col.Mobile;
newUser.CityId = $scope.col.UserAddress.CityId;

$http.post(API_URL + "/RegisterUser", { col: newUser }).success(function (response) {
    if(response.status=="success" && !response.mailError){
        $scope.register = false;
        $scope.alert = {type:'success', msg:"You are successfully registered. Please check mail for the password. If you do not see the mail, check spams"};
    }else if(response.mailError){
    $scope.alert = {type:'warning', msg:'Unable to send mail! please try forgot password next time you need to login'};
    }else{
        $scope.alert = {type:'danger', msg:response.msg};
    }
    $scope.loading = false;
});
  • 结果:调用成功,并调用Service中相关的Register函数。然而,接收到的NewUser对象的所有属性都被设置为NULL。
  • 这些值从JS端是正确的,所以在调用之间是不正确的。有什么建议吗?我的猜测是,我错过了一些明显的和非常小的,但似乎不能弄清楚的时刻。

    将复合类型从JS发送到WCF REST服务

    让它工作。这是需要修改的地方。

    我们只需要将user对象传递给服务,而不是使用col对象来包装user对象。所以不用

    $http.post(API_URL + "/RegisterUser", { col: newUser }).success(function (response) {
    

    我们称之为

    $http.post(API_URL + "/RegisterUser", newUser).success(function (response) {