簡體   English   中英

從iOS到RESTful WCF服務.NET 4.0的POST HTTP請求

[英]POST HTTP Request from iOS to RESTful WCF Service .NET 4.0

我正在嘗試向IIS7 .NET Framework 4.0上以C#編寫的WCF Web服務創建POST請求。

該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];

WCF Web服務的C#代碼:

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

我在iOS端記錄了響應,該響應顯示了服務器發生錯誤的XML響應,並檢查了服務器端日志,我似乎找不到任何問題。 任何幫助,將不勝感激。

我只能從服務器上找到日志,內容如下:

(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

通過創建一個類以將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; }
}

問題在於,您將操作的主體樣式聲明為Bare ,但您正在發送希望參數接收的數據,並包裝在參數名稱中。

如果您將操作聲明為

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

您可以根據需要將請求正文發送為{"zip":"30309"}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM