我有一个带有路由的HttpPOST .Net WebApi:http://blah/api/CarValues?userId=1&carId=5&value=12.12
。
此webApi在Azure上发布,我可以通过Postman调用它。但是,在我的swift应用程序内部,当我尝试将数据发布到此端点时,我得到了这个:
responseString = Optional("{\"Message\":\"No HTTP resource was found that matches the request URI \'http://blah.net/api/CarValues\'.\"}")
这是我目前的代码:
func postCarInfo() {
// Posts to cloud
var request = URLRequest(url: URL(string: webApiUrl)!)
request.httpMethod = "POST"
let postString = "userId=1&carId=5&value=200.00"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()
}
我不确定为什么这不起作用。我已经尝试通过postman成功多次击中此端点,我可以访问webApi中的其他get方法,而不是Post一个。我还设置NSAppTransportSecurity
以允许NSAllowsArbitraryLoads
,但我仍然无法访问端点。
非常感谢任何帮助
答案 0 :(得分:1)
也许这是相关的:
WebAPI - Attribute Routing POST not working with WebAPI Cors?
如果您将params包含在路径中,则params需要存在于URL中,而不是存在于请求的正文中。
试试这个:
let paramString = "userId=1&carId=5&value=200.00"
var request = URLRequest(url: URL(string: webApiUrl+"?"+paramString)!)
request.httpMethod = "POST"
let task = ...