WebAPI学习笔记(5)Asp.net调用WebAPI Post方法上传附件
1、WebAPI方法:
[HttpPost] public HttpResponseMessage TransferData(dynamic obj) { MethodReturnModel<string> returnModel = new MethodReturnModel<string>(); try { string connectorCode = obj.connectorCode.ToString(); string content = obj.contentJson.ToString(); string attachments = obj.attachments.ToString(); if (connectorCode == "" || content == "" || attachments == "") { returnModel.Result = false; returnModel.Message = "Connector code,content and attahments can be empty"; } else { List<AttachmentModel> attachmentList = MethodHelper.Json2List<AttachmentModel>(attachments); if (attachmentList != null) { string TempFileSavePath = ConfigurationHelper.GetDownloadFileDefaultSavePath(); for (int i = 0; i < attachmentList.Count; i++) { MethodHelper.ByteToFile(attachmentList[i].bytes, HttpContext.Current.Server.MapPath(TempFileSavePath + "/" + attachmentList[i].fileName)); } returnModel.Result = true; } else { returnModel.Result = false; returnModel.Message = "No attachment"; } } } catch (Exception ex) { returnModel.Result = false; returnModel.Message = ex.Message; } return MethodHelper.GetHttpResponseMessage(ConvertJson.GetJson<MethodReturnModel<string>>(returnModel)); }
2、调用方式:
//测试附件 string fileName1 = "Test001.txt"; string fileName2 = "Test002.pptx"; string fileName3 = "Test003.zip"; byte[] bytes1 = FileToByte(HttpContext.Current.Server.MapPath("Temp/" + fileName1)); byte[] bytes2 = FileToByte(HttpContext.Current.Server.MapPath("Temp/" + fileName2)); byte[] bytes3 = FileToByte(HttpContext.Current.Server.MapPath("Temp/" + fileName3)); List<AttachmentModel> attachmentList = new List<AttachmentModel>(); attachmentList.Add(new AttachmentModel(fileName1, bytes1)); attachmentList.Add(new AttachmentModel(fileName2, bytes2)); attachmentList.Add(new AttachmentModel(fileName3, bytes3)); string attachmentsJson = List2Json<AttachmentModel>(attachmentList); string Username = "xxx"; string Password = "xxx"; string Body = "{'connectorCode': '001', 'contentJson': { 'IssueKey': '009','IssueType': '111'}, 'attachments': '" + attachmentsJson + "'}"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{Username}:{Password}"))); HttpContent httpContent = new StringContent(Body, Encoding.UTF8); httpContent.Headers.Add("user-key", "xxx"); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); Uri address = new Uri("https://localhost:44300/api/issues/TransferData"); var response = client.PostAsync(address, httpContent).Result.Content.ReadAsStringAsync().Result;//返回值 }