2017-04-18 38 views
0

我新的iOS开发500错误。 GET方法正常工作。HTTP POST方法返回使用SWIFT的蔚蓝网络API服务器

GET

但是,POST方法将返回500响应..

POST

这是帖子控制器斯威夫特:

@IBAction func pressedPost(_ sender: Any) { 
    let restEndPoinst: String = "http://tresmorewebapi.azurewebsites.net/api/accounts" 
    guard let url = URL(string: restEndPoinst) else { 
     print("Error creating URL") 
     return 
    } 

    var urlRequest = URLRequest(url: url) 
    urlRequest.httpMethod = "POST" 
    urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") 
    // api key need urlRequest.setValue(<#T##value: String?##String?#>, forHTTPHeaderField: "APIKey") 


    let jsonDictionary = NSMutableDictionary() 
    jsonDictionary.setValue(9, forKey: "Id") 
    jsonDictionary.setValue("From iOS!", forKey: "UserName") 
    jsonDictionary.setValue("HAHAH iOS", forKey: "UserEmail") 
    jsonDictionary.setValue(200.44, forKey: "Rebate") 
    jsonDictionary.setValue(1200.20, forKey: "MemCom") 

    let jsonData: Data 
    do{ 
     jsonData = try JSONSerialization.data(withJSONObject: jsonDictionary, options: JSONSerialization.WritingOptions()) 
    } 
    catch{ 
     print("Error creating JSON") 
     return 
    } 

    let config = URLSessionConfiguration.default 
    let session = URLSession(configuration: config) 

    let task = session.dataTask(with: urlRequest, completionHandler: 
     { 
      (data: Data?, response: URLResponse?, error: Error?) in 
      print("Error:") 
      print(error) 
      print("response:") 
      print(response) 
      print("Data:") 
      print(String(data: data!, encoding: String.Encoding.utf8)) 
    }) 

    task.resume() 
} 

我的模型看起来象下面这样:

public class Account 
{ 
    public int Id { get; set; } 
    public string UserName { get; set; } 
    public string UserEmail { get; set; } 
    public decimal Rebate { get; set; } 
    public decimal MemCom { get; set; } 
} 

我,如果你搜索iOS Swift Calling POST, PUT and DELETE on Azure REST Web Service这是我继一个利用asp.net网页API 迅速和蔚蓝随后的Youtube教程。

请帮我如何解决POST请求的一些数据插入到我的蔚蓝的Web服务器。

+0

根据定义,500 HTTP状态代码是一个内部服务器错误。如果您的请求出现问题(例如,格式错误的有效负载),则应该收到4xx状态码,例如, 400或403.这似乎是服务器的问题。 – daltonclaybrook

+0

@daltonclaybrook不过,如果我使用HTTP邮差调试程序,我可以做POST和它完美的作品!但我不知道为什么的iOS提供了500错误 –

+0

其实,是有可能,你忘序列化JSON数据后,你的URLRequest的'httpBody'属性分配? – daltonclaybrook

回答

1

回答这个问题.. 我忘记httpbody

在这里,在做副渔获物是固定的POST:

do{ 
     jsonData = try JSONSerialization.data(withJSONObject: jsonDictionary, options: JSONSerialization.WritingOptions()) 
     urlRequest.httpBody = jsonData 
    }