我試圖調用Web api方法來保存文件數據。當我調試Webapi方法時,我發現ContentLength不是正確的,因爲當我檢索文件時,它顯示錯誤爲損壞的文件。如何將文件數據從C#控制檯應用程序傳遞給WebApi?
我的班級的方法是: -
using (var formData = new MultipartFormDataContent())
{
HttpContent stringContent = new StringContent(file);
formData.Add(stringContent, "file", file);
formData.Add(new StringContent(JsonConvert.SerializeObject(file.Length)), "ContentLength ");
HttpResponseMessage responseFile = client.PostAsync("Report/SaveFile?docId=" + docId, formData).Result;
}
我的Web API的方法是: -
[HttpPost]
public HttpResponseMessage SaveFile(long docId)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Unauthorized);
try
{
var httpRequest = HttpContext.Current.Request;
bool IsSuccess = true;
if (httpRequest.Files.Count > 0)
{
var docfiles = new List<string>();
foreach (string file in httpRequest.Files)
{
HttpPostedFile postedFile = httpRequest.Files[file];
// Initialize the stream.
Stream myStream = postedFile.InputStream;
myStream.Position = 0;
myStream.Seek(0, SeekOrigin.Begin);
var _item = CorrectedReportLibrary.Services.ReportService.SaveFile(myStream,docId);
response = Request.CreateResponse<bool>((IsSuccess)
? HttpStatusCode.OK
: HttpStatusCode.NoContent,
IsSuccess);
}
}
}
catch (Exception ex)
{
Theranos.Common.Library.Util.LogManager.AddLog(ex, "Error in CorrectedReportAPI.Controllers.SaveDocument()", null);
return Request.CreateResponse<ReportDocumentResult>(HttpStatusCode.InternalServerError, null);
}
return response;
}
如何設置從C#類方法的ContentLength
?
下面的代碼我加你告知,但還是同樣的問題出現以後,IDS文件已損壞ed:contents.Add(new StreamContent(stre),「file」,file); var result = await client.PostAsync(「ReportInfo/SaveFile?docId =」+ docId,contents); – jack123
@gorakh更新服務器端示例 – Hypnobrew