【问题标题】:Can't call Web Api by Alamofire.upload multipartFormData无法通过 Alamofire.upload multipartFormData 调用 Web Api
【发布时间】:2018-11-27 01:48:45
【问题描述】:

我有一个使用以下方法的 Windows WEB API:

public async Task<IHttpActionResult> SaveContract([FromBody] ModelDTO model)
{
  string custName = model.CustomerName;
  ...
}

我想要的模型如下所示:

public class ModelDTO
    {      
        public int CustomerNumber { set; get; }        
        public string CustomerName { set; get; }
        public string CustomerMail { set; get; }        
        public string imageDataBase64 { set; get; }
    }      

我想用我的 iOS 应用 (Swift 4) 和 Alamofire 4.7.2 调用 API 我的开发服务器有一个自签名证书。所以我需要禁用评估。

let defaultManager: Alamofire.SessionManager = {
        let serverTrustPolicies: [String: ServerTrustPolicy] = [
            "devserver": .disableEvaluation           
        ]

        let configuration = URLSessionConfiguration.default
        configuration.httpAdditionalHeaders =   Alamofire.SessionManager.defaultHTTPHeaders

        return Alamofire.SessionManager(
            configuration: configuration,
            serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies))
    }()


let webApi: String = "https://devserver:7208/api/KP/SaveContract"

let data = UIImageJPEGRepresentation(photoImageView.image!,1) //got the Data form an image view

var imgString: String = ""

imgString = data.base64EncodedString()

let Param =  Parameters = [
                "CustomerNumber": 1,               
                "CustomerName": "Test Name",
                "CustomerMail": "test@test.com",                
                "imageDataBase64": imgString]

defaultManager.upload(
        multipartFormData: { multipartFormData in
            for (key, value) in contAsJsonParam {
            multipartFormData.append("\(value)".data(using: .utf8)!, withName:key)
            }            
        },
        to: webApi,
        encodingCompletion: { encodingResult in
                        switch encodingResult {
                            case .success(let upload, _, _):
                                    upload.responseJSON { response in
                                    debugPrint(response)
                                        //lbl sichtbar machen
                                    }
                            case .failure(let encodingError):
                            print(encodingError)
                            }
            })

使用 Alamofire.request 调用没有图像的 api 有效,但使用图像请求,它不起作用。 (错误的 ssl 错误) 所以我尝试了上传方法,但上传不以任何方式工作(有或没有图像字符串)

如果我用 Alamofire.upload 调用 Api,我得到一个 system.net.http.unsupportedmediatypeexception

"没有 MediaTypeFormatter 可用于读取类型的对象 来自媒体类型为“multipart/form-data”的内容的“ModelDTO”。”

我尝试通过“headers: Content-Type:application/json”将上传类设为json 但没有效果。

我尝试通过放置来修复它

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/form-data"));

在 WebApiConfig 中。然后我得到了另一个错误 我在“string custName = model.CustomerName;”行的 api 中得到了 NullReferenceException

【问题讨论】:

    标签: c# ios swift alamofire


    【解决方案1】:

    您可以使用此代码。我已经用多部分数据测试了这段代码。它对我来说很好。

        let url = "https://devserver:7208/api/KP/SaveContract"
            //imp data need to be dynamic
    
            let parameters: NSMutableDictionary = ["userId":"1123",
                                                   "caption":"hello how are you",
                                                   "keyword":"First Post",
                                                   "askPrice":"12345",
                                                   "postScope":"1",
                                                   "commentStatus":"1",
                                                   "gender":"male",
                                                   "email":"asd@asd.com"
                                                  ]
    
            var dictionaryHeaders = [String : String]()
            dictionaryHeaders = ["Content-Type": "application/x-www-form-urlencoded" ]
    
    
            Alamofire.upload(multipartFormData: { (multipartFormData) in
                for (key, value) in parameters {
                    multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as! String)
                }
    
    
                self.postImage = UIImage(named:"YOUR IMAGE NAME")
    
    
                    if let data = UIImageJPEGRepresentation(self.postImage,1) {
                        multipartFormData.append(data, withName: "postPic", fileName: "image.png", mimeType: "image/png")
                    }
    
    
    
            }, usingThreshold: UInt64.init(), to: url, method: .post, headers: dictionaryHeaders ) { (result) in
                switch result{
                case .success(let upload, _, _):
                    upload.responseJSON{ response in
    
                        print(response)
                    }
                case .failure(let error):
                    print("Error in upload: \(error.localizedDescription)")
                }
            }
    

    【讨论】:

    • 我试试你的代码。我改变的东西: - url 到我的 url - 参数到我的参数修复修复值 - “dictionaryHeaders” 只削减到 [“Content-Type”:“application/x-www-form-urlencoded”] -replace “alamofire.upload " 与我的 sessionmaager "defaultManager.upload" - 将图像部分注释掉。 (仅使用 for key value 部分)结果:相同的错误
    • 你能发布你的 API 方法吗?
    猜你喜欢
    • 1970-01-01
    • 2022-01-23
    • 2012-03-17
    • 2018-05-24
    • 1970-01-01
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多