WCF REST服务发布错误与iOS客户端
本文关键字:错误 iOS 客户端 REST 服务 布错误 WCF | 更新日期: 2023-09-27 18:07:05
我已经将WCF服务发布到IIS,并且可以通过get方法成功地获取所有数据。我没有尝试将数据POST到服务并将此数据保存在数据库中。我得到的确切错误是:
服务器在处理请求时遇到错误。异常消息是"对象引用未设置为对象的实例"。
此错误消息总是在发送请求后返回给客户端的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];
}
尝试从WebInvoke属性中删除BodyStyle = WebMessageBodyStyle.WrappedRequest
并添加RequestFormat=WebMessageFormat.Json
,像这样。
[OperationContract]
[WebInvoke(Method = "POST",RequestFormat=WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/NewUser")]
void AddNewUser(NewUser newUser);
我已经测试了它,这是为我工作。