首页 > 解决方案 > 如何在 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);
            });

问题是文件已下载但未打开并出现错误。

(文件大小为 17kb) 在此处输入图像描述

标签: c#asp.net-mvcpdfdownloadwebapi

解决方案


推荐阅读