簡體   English   中英

iOS客戶端的WCF REST服務POST錯誤

[英]WCF REST Service POST Error with iOS Client

我已經將WCF服務發布到IIS,並且可以使用GET方法成功獲取所有數據。 我不是在嘗試將數據發布到服務並將此數據保存在數據庫中。 我得到的確切錯誤是:

服務器在處理請求時遇到錯誤。 異常消息是“對象引用未設置為對象的實例”。 有關更多詳細信息,請參見服務器日志。

發送請求后,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);

我已經測試過了,這對我有用。

暫無
暫無

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

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