我在互联网上看到过使用json消费WCF服务的各种例子,但是没有看到使用iOS消费它的完整示例,也没有成功创建一个简单的json调用到iOS的wcf服务。 / p>
我在wcf中有一个服务接口:
[ServiceContract(Namespace = "")]
[DataContractFormat(Style = OperationFormatStyle.Document)]
public interface IService
{
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "referenceData")]
string GetReferenceData(string referenceName);
}
在我的类实现中,我也有以下属性:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehaviorAttribute(IncludeExceptionDetailInFaults = true)]
我试图从iOS中检索:
NSArray *keys = [NSArray arrayWithObjects:@"referenceName", nil];
NSArray *objects = [NSArray arrayWithObjects:@"test", nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSData *jsonData = nil;
NSString *jsonString = nil;
if([NSJSONSerialization isValidJSONObject:jsonDictionary])
{
jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:nil];
jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"%@", jsonString);
}
NSURL *url = [NSURL URLWithString:@"http://test.com/Service.TestService.svc"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-type"];
[request setValue:jsonString forHTTPHeaderField:@"json"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:jsonData];
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned) {
}
else {
NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", response);
}
有人能指出我正确的方向吗?当我使用WCF测试客户端测试我的服务时,我得到了一个json响应,但是当我从iOS代码运行我的调用时,没有抛出错误,我的响应只是空的。
答案 0 :(得分:1)
我建议您使用Fiddler检查来自iOs的请求,并将其与WCF测试客户端的请求进行比较。
答案 1 :(得分:1)
问题在于配置。我在代码项目中找到了一个演练:How to create a JSON WCF RESTful Service in 60 seconds正确设置。