c# – 如何使用Web API返回文件?
发布时间:2020-12-16 01:20:50 所属栏目:百科 来源:网络整理
导读:我正在使用ASP.NET Web API.我想从API(API生成)下载带有C#的PDF. 我可以让API返回一个byte []吗?对于C#应用程序,我可以这样做: byte[] pdf = client.DownloadData("urlToAPI");? 和 File.WriteAllBytes()? 解决方法 最好使用StreamContent返回HttpResponse
我正在使用ASP.NET Web API.我想从API(API生成)下载带有C#的PDF.
我可以让API返回一个byte []吗?对于C#应用程序,我可以这样做: byte[] pdf = client.DownloadData("urlToAPI");? 和 File.WriteAllBytes()? 解决方法
最好使用StreamContent返回HttpResponseMessage.
这是一个例子: public HttpResponseMessage GetFile(string id) { if (String.IsNullOrEmpty(id)) return Request.CreateResponse(HttpStatusCode.BadRequest); string fileName; string localFilePath; int fileSize; localFilePath = getFileFromID(id,out fileName,out fileSize); HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); response.Content = new StreamContent(new FileStream(localFilePath,FileMode.Open,FileAccess.Read)); response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment"); response.Content.Headers.ContentDisposition.FileName = fileName; response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf"); return response; } 来自patridge的评论UPD: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |