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

时间:2014-03-13 13:03:13

标签: c# jquery ajax json wcf

我正在使用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调用它返回错误。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

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

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

您的服务合同。

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

的Ajax:

type: "POST",