2013-01-10 47 views
0

我正嘗試創建一個POST請求到在IIS7 .NET Framework 4.0上運行的C#編寫的WCF Web服務。從iOS到RESTful WCF服務.NET 4.0 POST HTTP請求

Web服務適用於GET請求,但我似乎無法獲得POST方法的工作。一些背景是,我必須切換到.NET之前使用PHP的服務器端。

代碼爲我在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#代碼WCF Web服務:

[OperationContract] 
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/weather")] 
List<Weather> GetWeatherMethod(string zip); 

我登錄,顯示來自服務器的XML響應在iOS端的響應,一個發生錯誤,並檢查服務器端日誌,我似乎無法找到任何錯誤。任何幫助,將不勝感激。

只記錄從服務器中我能找到寫着:

(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 
+0

你能發佈更多的服務器調試輸出嗎?像webmethod有史以來得到執行?什麼錯誤面臨? –

+0

我可以在哪裏找到服務器上的詳細日誌?我似乎只有一個日誌文件,顯示每個請求對服務器和從什麼IP。從我所知道的情況來看,它不會更新日誌 –

+0

我不喜歡在日誌中看到「400」,請儘可能添加響應標題和內容。 –

回答

0

的問題是,你聲明的操作體風格Bare,但是你發送你想要的參數來接收參數名稱參數包裹數據。

如果聲明爲

[OperationContract] 
[WebInvoke(Method = "POST", 
      RequestFormat = WebMessageFormat.Json, 
      ResponseFormat = WebMessageFormat.Json, 
      BodyStyle = WebMessageBodyStyle.WrappedRequest, 
      UriTemplate = "/weather")] 
List<Weather> GetWeatherMethod(string zip); 

,只要你想你可以發送請求體作爲{"zip":"30309"}操作。

0

之所以能夠通過創建一個類,使得JSON將映射到它來解決這個問題。

[OperationContract] 
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/weather")] 
List<Weather> GetWeatherMethod(ZipCodeJSON zipJson); 

[DataContract] 
public class ZipCodeJSON 
{ 
    [DataMember] 
    public string zip { get; set; } 
}