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

标签 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 应用程序 (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

"No MediaTypeFormatter is available to read an object of type 'ModelDTO' from content with media type 'multipart/form-data'."

我尝试通过“headers: Content-Type:application/json”将上传类设置为 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)")
            }
        }

关于c# - 无法通过 Alamofire.upload multipartFormData 调用 Web Api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50905670/

相关文章:

c# - 在 C# 中从 WebClient 读取响应 header

c# - 基于泛型参数实例化具体类c#

swift - CloudRun 中的 Apple SwiftNIO - 这可能吗?

c# - 向面板发送 WM_SETREDRAW 消息后刷新

c# - 更改每个文件的下载位置和名称

ios - 来自 NSObject 的 PresentViewController?

iphone - 如何在 iOS 应用程序中从 OBD 访问数据

iOS - 导航栏背景和 UIView 背景之间的颜色差异

ios - Swift 枚举函数仅适用于枚举的单个案例?

ios - 获取内存不足崩溃的通知