我正在尝试连接到我在另一台计算机上运行的 ASP.NET Core API。我想尝试使用 POST 请求添加数据。我收到这些错误消息:
连接 6:默认 TLS 信任评估失败 (-9813)
连接 6:TLS 信任遇到错误 3:-9813
连接 6:遇到错误(3:-9813)
错误描述为:
该服务器的证书无效。您可能正在连接到冒充“192.168.0.100”的服务器,这可能会使您的 secret 信息面临风险。
let jsonData = try? JSONSerialization.data(withJSONObject: data)
let url = URL(string: "https://192.168.0.100:5001/api/Trips")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription)
return
}
let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
if let responseJSON = responseJSON as? [String: Any] {
}
}
task.resume()
我目前不担心任何风险,因为这只是出于开发目的。有没有办法信任连接或完全忽略检查?
最佳答案
我终于明白了。
我使用这些设置创建了 session 对象:
let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: OperationQueue.main)
我将此扩展添加到代码底部:
extension MyViewController : URLSessionDelegate {
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
}
}
在部署应用程序时,为了安全起见,请不要忘记删除它。
我希望我能帮助别人。感谢大家的建议。这就是我的代码现在的样子:
import UIKit
class MyViewController: UIViewController {
@IBOutlet weak var createButton: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func createButtonTapped(_ sender: Any) {
let data: [String: Any] = ["data1": data1, "data2": data2......]
let jsonData = try? JSONSerialization.data(withJSONObject: data)
let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: OperationQueue.main)
let url = URL(string: "https://192.168.0.100:5001/api/Trips")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = jsonData
request.addValue("application/json",forHTTPHeaderField: "Content-Type")
request.addValue("application/json",forHTTPHeaderField: "Accept")
let task = session.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription)
return
}
let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
if let responseJSON = responseJSON as? [String: Any] {
.....
}
}
task.resume()
}
}
extension MyViewController : URLSessionDelegate {
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
}
}
关于swift - 该服务器的证书无效(错误 : 9813 ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59107359/