无法通过Alamofire.upload调用Web Api multipartFormData

时间:2018-06-18 08:45:21

标签: c# ios swift alamofire

我有一个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 App(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

  

&#34;没有MediaTypeFormatter可用于读取类型的对象   &#39; ModelDTO&#39;来自媒体类型的内容&#39; multipart / form-data&#39;。&#34;

我尝试通过at&#34; headers将上传类设为json:Content-Type:application / json&#34; 但没有效果。

我尝试通过添加

来修复它
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/form-data"));
WebApiConfig中的

。然后我又得到了一个错误 我在api的第#34号字符串中得到了NullReferenceException;字符串custName = model.CustomerName;&#34;

1 个答案:

答案 0 :(得分:0)

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

    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)")
            }
        }