Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/apache-flex/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Can';t通过Alamofire调用Web Api.upload multipartFormData_C#_Ios_Swift_Alamofire - Fatal编程技术网

C# Can';t通过Alamofire调用Web Api.upload multipartFormData

C# Can';t通过Alamofire调用Web Api.upload multipartFormData,c#,ios,swift,alamofire,C#,Ios,Swift,Alamofire,我有一个Windows WEB API,其方法如下: public async Task<IHttpActionResult> SaveContract([FromBody] ModelDTO model) { string custName = model.CustomerName; ... } 我想用我的iOS应用程序(Swift 4)和Alamofire 4.7.2调用API 我的开发服务器有一个自签名证书。所以我需要禁用评估 let defaultManager:

我有一个Windows WEB API,其方法如下:

public async Task<IHttpActionResult> SaveContract([FromBody] ModelDTO model)
{
  string custName = model.CustomerName;
  ...
}
我想用我的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错误) 所以我尝试了upload方法,但upload在任何情况下都不起作用(有或没有图像字符串)

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

“没有MediaTypeFormatter可用于读取类型为的对象 “ModelDTO”来自媒体类型为“多部分/表单数据”的内容。“

我试图通过“headers:Content-Type:application/json”将upload类设置为json 但没有效果

我试着把它放在

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/form-data"));
在WebApiConfig中。然后我又犯了一个错误
我在api的“string custName=model.CustomerName;”行中得到了一个NullReferenceException。您可以使用此代码。我已经用多部分数据测试了这段代码。这对我来说很好

    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”仅缩减为[“内容类型”:“application/x-www-form-urlencoded”]-将“alamofire.upload”替换为我的SessionMager“defaultManager.upload”-将图像部分注释掉。(仅用于键值部分)结果:相同错误您可以发布您的API方法吗?
    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)")
            }
        }