将字节数组从后面的代码发送到 ajax 调用

Send byte array from code behind to ajax call

我有一个网络方法,我将 HTML 转换为 PDF,然后将其保存到本地文件夹,我希望用户下载该文件而不返回 post,所以我正在尝试对 Web 方法进行 AJAX POST 调用以获取字节数组,然后将其转换为 PDF,问题是我收到错误 500:

{Message: "There was an error processing the request.", StackTrace: "", ExceptionType: ""}

虽然我知道 web 方法触发,因为当放置断点时它会停在那里,我实际上可以看到 return 之前的二进制数组以及文件夹中创建的文件,我仍然得到错误信息,这里是我的代码:

C#:

[WebMethod]
public static byte[] getfile(string one, string two)
{
    HttpContext context = HttpContext.Current;
    HtmlToPdf converter = new HtmlToPdf();

    converter.Options.MinPageLoadTime = 10;
    converter.Options.MaxPageLoadTime = 30;

    PdfDocument doc = converter.ConvertUrl("http://localhost/dashboard_pdf.aspx?one=" + one+ "&" + "two=" + two);

    string appPath = HttpContext.Current.Request.ApplicationPath;
    Random rnd = new Random();
    int num = rnd.Next(1, 1000000);
    string path = context.Server.MapPath(appPath + "/Web/" + num + ".pdf");

    doc.Save(path);   
    doc.Close();

    FileStream stream = File.OpenRead(path);
    byte[] fileBytes = new byte[stream.Length];

    stream.Read(fileBytes, 0, fileBytes.Length);
    stream.Close();

    byte[] b1 = System.IO.File.ReadAllBytes(path);

    return fileBytes;
}

JS:

$.ajax({
    type: "POST",
    url: "dashboard.aspx/getfile",
    contentType: "application/json; charset=utf-8",
    data: "{'one':\"" + one+ "\", 'two':\"" + two + "\" }",
    dataType: "json",
    processData: false,
    success: function (data) {
        data = data.d;

        var byteArray = new Uint8Array(data);
        var a = window.document.createElement('a');

        a.href = window.URL.createObjectURL(new Blob([byteArray], { type: 'application/pdf' }));

        a.download = "Dashboard";

        document.body.appendChild(a)
        a.click();
        document.body.removeChild(a)
    }
});

有什么想法吗?

谢谢。

我通过将其添加到我的 web.config:

来解决这个问题
 <system.web.extensions>
    <scripting>
      <webServices>
        <!-- Update this value to change the value to a larger value that can accommodate your JSON Strings -->
        <jsonSerialization maxJsonLength="86753090" />
      </webServices>
    </scripting>
  </system.web.extensions>
 var jsonResult = Json(model, JsonRequestBehavior.AllowGet);
            jsonResult.MaxJsonLength = int.MaxValue;
            return jsonResult;

这样你就return最大的字节数组并且可以转换为PDF并下载