如何下载从WCF服务返回的流和从jquery调用ajax调用的WCF服务

本文关键字:服务 调用 WCF jquery 何下载 ajax 下载 返回 | 更新日期: 2023-09-27 17:49:55

我正在使用JQuery从客户端使用WCF服务方法。我想保存从客户端WCF方法返回的流数据。以下WCF方法工作良好,其中我使用我们自己的excelExport的方法来创建内存流-

public System.IO.Stream TestExportToExcel()
    {
        using (_oxBowData = new Data.OxbowDataContext())
        {
            ExcelExport excelExport = new ExcelExport();
            List<SheetData> sheets = new List<SheetData>();
            sheets.Add(new SheetData()
            {
                SheetName = "sheet1",
                DataList = _oxBowData.GetLunchReportData(new DateTime(2013, 12, 24)).ToList<object>()
            });
            using (MemoryStream xlsstream = excelExport.ExportToExcelToStream(sheets))
            {
                xlsstream.Position = 0L;
                return xlsstream;
            }
        }
    }

服务合同:

[OperationContract]
[WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json, UriTemplate = "TestExportToExcel")]
System.IO.Stream TestExportToExcel();

以下是我在客户端使用的,但它只是返回我错误-

$.ajax({
                type: "GET",
                url: u + "/Terminal/ManagementService.svc/TestExportToExcel",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                processData: false,
                success: function (data) {
                    alert(JSON.stringify(data));
                },
                error: function (data) {
                    alert(JSON.stringify(data));
                }
            });

当我调用这个客户端ajax调用它返回错误。有人能帮忙吗?

如何下载从WCF服务返回的流和从jquery调用ajax调用的WCF服务

实际上,问题是您在JSON中指定RequestFormat = WebMessageFormat.Json,而您的方法System.IO.Stream TestExportToExcel()没有任何参数来接收它。

此外!. net强制你指定RequestFormat如果你使用POST方法。所以,像这样修改你的合同。

您的服务合同。

[OperationContract]
[WebInvoke(Method = "POST", 
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare, 
ResponseFormat = WebMessageFormat.Json, 
UriTemplate   = "TestExportToExcel")]
System.IO.Stream TestExportToExcel(MyCustomObject jsonRequest);
Ajax:

type: "POST",