iOS客户端的WCF REST服务POST错误

时间:2014-06-07 05:02:25

标签: c# ios wcf rest

我已经向IIS发布了WCF服务,并且可以使用GET方法成功获取所有数据。我不是试图将数据发布到服务并将此数据保存在数据库中。我得到的确切错误是:

服务器在处理请求时遇到错误。异常消息是“对象引用未设置为对象的实例。”。有关详细信息,请参阅服务器日志。

此错误消息始终在发送请求后返回给客户端的REST响应中返回。

我已经进入了inetpub-> wwwroot-> logs文件夹并环顾四周,但没有在日志文件中看到任何帮助我查明问题的内容。我认为问题在于我是如何构建服务器以接受响应的,或者我是如何从客户端发送响应的。我是REST的新手,所以我不太确定我做错了什么。下面是代码。任何帮助将不胜感激。

//服务器代码:

// IService.cs

    [OperationContract]
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/NewUser")]
    void AddNewUser(NewUser newUser);


[DataContract]
public class NewUser
{
    [DataMember]
    public string name { get; set; }



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

// Service1.svc.cs

public  void AddNewUser(NewUser newUser)
{
    var userController = new UserController();

    userController.AddNewUser(newUser.name, newUser.age);
}

// iPhone上的客户端代码

 NSArray *propertyNames = [NSArray arrayWithObjects:@"name", @"age",nil];
    NSArray *propertyValues = [NSArray arrayWithObjects:@"Test", @"100",nil];

    NSDictionary *properties = [NSDictionary dictionaryWithObjects: propertyValues forKeys:propertyNames];

    NSMutableDictionary *newUserObject = [NSMutableDictionary dictionary];

    [newUserObject setObject:properties forKey:@"newusermodel"];

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:newUserObject options:kNilOptions error:nil];

    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

       NSString *urlString = [NSString stringWithFormat:@"http://myPublicIPAddress/MyService/Service1.svc/NewUser"];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    [request setValue:jsonString forHTTPHeaderField:@"json"];

    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:jsonData];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

    NSError *error = nil;
    NSURLResponse *theResponse = [[NSURLResponse alloc]init];
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&error];

    if(error)
    {
        txtData.text = [error localizedDescription];
    }

    else
    {
        NSMutableString *retVal = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    }

1 个答案:

答案 0 :(得分:1)

尝试从WebInvoke属性中删除BodyStyle = WebMessageBodyStyle.WrappedRequest,然后像这样添加RequestFormat=WebMessageFormat.Json

  [OperationContract]
  [WebInvoke(Method = "POST",RequestFormat=WebMessageFormat.Json, ResponseFormat =        WebMessageFormat.Json, UriTemplate = "/NewUser")]
  void AddNewUser(NewUser newUser);

我测试了它,这对我有用。