ServiceStack客户端添加附件

Fla*_*cks 4 c# soap servicestack

我正在使用ServiceStack.ServiceClient.Web.XmlServiceClient连接到Web服务.有没有办法为请求添加附件?

更多信息:

我想要做的是避免使用Microsoft.Web.Services2,因为我使用的是Mono.我正在尝试上传XML数据文件以及XML请求.就像这个问题一样: 通过C#.net中的webservice将报表单元上传到jasperserver

myt*_*thz 14

要上传文件,最好(也是最快)的方法是不将其编码为普通请求变量,而只是将其作为普通HTTP上传与ContentType multipart/form-data上传到Web服务,即HTML表单当前如何将文件发送到网址.

ServiceStack内置支持以这种方式处理上传文件,其中有一个完整的示例,说明如何在ServiceStack的RestFiles示例项目中执行此操作.

要使用ServiceClient上载文件,您可以使用此示例中显示.PostFile <T>()方法:

var fileToUpload = new FileInfo(FilesRootDir + "TESTUPLOAD.txt");

var response = restClient.PostFile<FilesResponse>(WebServiceHostUrl + "files/README.txt",
    fileToUpload, MimeTypes.GetMimeType(fileToUpload.Name));
Run Code Online (Sandbox Code Playgroud)

所有上传的文件都可以通过base.RequestContext.Files集合使用,您可以使用SaveTo()方法(作为Stream或文件)轻松处理.

foreach (var uploadedFile in base.RequestContext.Files)
{
    var newFilePath = Path.Combine(targetDir.FullName, uploadedFile.FileName);
    uploadedFile.SaveTo(newFilePath);
}
Run Code Online (Sandbox Code Playgroud)

类似地,与返回文件响应(作为附件或直接)相关,您只需要在HttpResult中返回FileInfo,如:

return new HttpResult(FileInfo, asAttachment:true);
Run Code Online (Sandbox Code Playgroud)

多个文件上传

您还可以使用PostFilesWithRequest所有.NET服务客户端中提供的API在单个HTTP请求中上载多个流.除了多个文件上传数据流之外,它还支持使用QueryString 和POST'ed FormData的任意组合填充Request DTO ,例如:

using (var stream1 = uploadFile1.OpenRead())
using (var stream2 = uploadFile2.OpenRead())
{
    var client = new JsonServiceClient(baseUrl);
    var response = client.PostFilesWithRequest<MultipleFileUploadResponse>(
        "/multi-fileuploads?CustomerId=123",
        new MultipleFileUpload { CustomerName = "Foo,Bar" },
        new[] {
            new UploadFile("upload1.png", stream1),
            new UploadFile("upload2.png", stream2),
        });
}
Run Code Online (Sandbox Code Playgroud)

仅使用类型化请求DTO的示例.在JsonHttpClient还包括异步当量为每个的PostFilesWithRequestAPI的:

using (var stream1 = uploadFile1.OpenRead())
using (var stream2 = uploadFile2.OpenRead())
{
    var client = new JsonHttpClient(baseUrl);
    var response = await client.PostFilesWithRequestAsync<MultipleFileUploadResponse>(
        new MultipleFileUpload { CustomerId = 123, CustomerName = "Foo,Bar" },
        new[] {
            new UploadFile("upload1.png", stream1),
            new UploadFile("upload2.png", stream2),
        });
}
Run Code Online (Sandbox Code Playgroud)