gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:24:32 25 4
gpt4 key购买 nike

我有一个使用以下方法的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com