I am trying to create a POST request out to a WCF web service written in C# running on IIS7 .NET Framework 4.0.
The web service works for GET requests however I cannot seem to get POST methods working. Some background is that I was using PHP for the server side before having to switch to .NET.
Code for my request in iOS:
NSArray *jsonKeys = [NSArray arrayWithObjects:@"zip", nil];
NSArray *jsonValues = [NSArray arrayWithObjects: zipcode, nil];
NSDictionary *jsonDict = [NSDictionary dictionaryWithObjects:jsonValues forKeys:jsonKeys];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"%@", jsonString);
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/weather", ConnectionString3]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:jsonData];
C# Code for WCF Web service:
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/weather")]
List<Weather> GetWeatherMethod(string zip);
I logged the response on the iOS side which shows an XML response from the server that an error occurred and to check the server side log, which I can’t seem to find anything wrong with. Any help would be appreciated.
Only log from the server I can find reads:
(Date and Time) (Server IP) POST /PeopleService/PeopleService.svc/weather - 80 - (local app ip) AppName/1.0+CFNetwork/609+Darwin/11.4.2 400 0 0 0
The problem is that you declared the body style of the operation as
Bare, but you’re sending the data you want the parameter to receive wrapped in the parameter name.If you declare the operation as
You can send the request body as
{"zip":"30309"}as you want.