c# - 如何在 ActionResult Asp.net Mvc C# 中从 WebApi 下载文件
问题描述
一个被调用的方法GetFile
被写入一个WebApi
返回的项目中HttpResponseMessage
:
WebApi 控制器 I am using NReco.PdfGenerated library
[HttpGet]
[Route("GetFile")]
[NoCache]
public HttpResponseMessage GetFile()
{
try
{
var httpRequest = HttpContext.Current.Request;
var html = HttpUtility.UrlDecode(httpRequest.Headers["_GetFile"] ?? "");
if (string.IsNullOrWhiteSpace(html))
{
return null;
}
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(new MemoryStream(new HtmlToPdfConverter().GeneratePdf(html)))
};
response.Content.Headers.ContentType =
new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
return response;
}
catch
{
}
return null;
}
在另一个项目中,我想通过连接到该GetFile
方法ActionResult
并获取该文件。ActionResult 的写法如下:
请求类:
public class GeneratedHtmlToPdfRequest
{
[AllowHtml]
public string Html { get; set; }
}
控制器(Asp.net Mvc):
[HttpPost]
public ActionResult GeneratedHtmlToPdf(GeneratedHtmlToPdfRequest request)
{
var userData = CookieController.GetUserDataCookie(CookieController.SGP_PORTAL_ALL_USER);
string encodeText = HttpUtility.UrlEncode(request.Html);
var response = var response = WebController.CallApiWithHeader(
"http://baseUrlWebApi.com" , "GetFile",
"_GetFile",
encodeText).Result; //call web api method
var result = response.ReadAsByteArrayAsync().Result;
TempData[WebVariables.TEMP_DATA_FILE] = result;
return Json(new PostGeneratedHtmlToPdf()
{
RedirectUrl = WebController.GetCurrentWebsiteRoot() + "***/***/FileDownload/" + DateTime.Now.ToString("yyyyMMddHHmmss")
});
}
[HttpGet]
public virtual ActionResult FileDownload(string id)
{
var tempByte = (byte[]) TempData[WebVariables.TEMP_DATA_FILE];
TempData[WebVariables.TEMP_DATA_FILE] = tempByte;
return File(tempByte , "application/pdf" , id);
}
功能(调用网络API)
public static async Task<HttpContent> CallApiWithHeader(string url ,string methodName , string headerName = "", string header = "")
{
try
{
HttpClient client = new HttpClient {BaseAddress = new Uri(url)};
client.DefaultRequestHeaders.Add(headerName , header);
return client.GetAsync(methodName).Result.Content;
}
catch (Exception ex)
{
return null;
}
}
jquery
写的是调用GeneratedHtmlToPdf
方法:
window.$('body').on('click',
'#bDownload',
function(event) {
event.preventDefault();
var html = window.$('#layoutLegalBill').html();
window.$('#layoutLegalBill').html(ShowLayoutLoading());
const formData = new FormData();
formData.append('request.Html', html);
var xmlHttpRequest = new XMLHttpRequest();
if (!window.XMLHttpRequest) {
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttpRequest.open(
"POST",
'@Url.Action("GeneratedHtmlToPdf", "***", new {area = "***"})',
true);
xmlHttpRequest.onerror = function() {
ShowAlert(ErrorText(), 'dark', true);
};
xmlHttpRequest.onloadend = function() {
window.$('#layoutLegalBill').html(html);
var response = ParseJson(xmlHttpRequest.responseText);
window.location = response.RedirectUrl;
}
xmlHttpRequest.send(formData);
});
问题是文件已下载但未打开并出现错误。
解决方案
推荐阅读
- c# - Windows 窗体 - 导航栏 - 如何滑动?
- javascript - 将动画画布设置为标题标签的背景剪辑文本的方法?
- react-native - 背景提取在独立应用程序中不起作用
- javascript - JavaScript 搜索对象数组并返回父级索引
- html - css height 属性不适用于 html img 但 width 确实
- jquery - 使用 jquery 按类显示/隐藏附近的元素
- jquery - 为什么我的 jQuery .click() 函数不起作用?我很难过
- lua - 如何从变量运行lua字节码?
- docker - 气流 dag 导入错误没有这样的文件或目录
- javascript - 为什么我的回报被忽略了,而我却得到了承诺