如何使用 ServiceStack 客户端使用文件 [英] How to consume a file with a ServiceStack client

查看:43
本文介绍了如何使用 ServiceStack 客户端使用文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 ServiceStack 以 RESTful 方式将文件返回给 ServiceStack 客户端.

I am trying to use ServiceStack to return a file to a ServiceStack client in a RESTful manner.

我已阅读有关 SO 的其他问题(此处此处) 建议使用 HttpResult 和 FileInfo 对象或 MemoryStream 以允许将 ContentType 标头更改为相关文件类型.

I have read other questions on SO (here and here) which advise using HttpResult and a FileInfo object or MemoryStream to allow the ContentType header to be changed to the relevant file type.

当我通过浏览器调用服务时,这对我有用,正确的文件会自动开始下载.我如何使用 ServiceStack 客户端之一使用文件?

This works for me when I call the service via a browser, the correct file automatically starts to download. How do I consume the file using one of the ServiceStack clients though?

我正在使用请求 DTO 并尝试使用类似的东西返回

I'm using a Request DTO and trying to return using something similar to

return new HttpResult(new FileInfo("file.xml"), asAttachment:true) {
   ContentType = "text/xml"
};

例如,我将如何使用 JsonServiceClient 使用它?

How would I consume this with the JsonServiceClient for example?

推荐答案

您不会使用 ServiceStack 的 .NET ServiceClients,因为它们主要用于发送 DTO.

You wouldn't consume files with the ServiceStack's .NET ServiceClients as they're mainly for sending DTO's.

你可以使用任何普通的WebRequest来下载文件,ServiceStack的v3.9.33中引入了一些方便的 WebRequest 扩展 HTTP Utils 使这变得容易,例如:

You can just use any normal WebRequest to download files, in the v3.9.33 of ServiceStack introduced some handy WebRequest extensions HTTP Utils that make this easy, e.g:

对于文本文件:

var xmlFile = downloadUrl.GetXmlFromUrl(responseFilter: httpRes => {
        var fileInfoHeaders = httpRes.Headers[HttpHeaders.ContentDisposition];
    });

其中 fileInfoHeaders 包含 W3C ContentDisposition HTTP 标头,例如返回 FileInfo 时,ServiceStack 返回:

Where fileInfoHeaders contains the W3C ContentDisposition HTTP Header, e.g. when returning a FileInfo, ServiceStack returns:

attachment;filename="file.xml";size={bytesLen};
creation-date={date};modification-date={date};read-date={date};

要下载二进制文件,您可以使用:

To download a binary file you can use:

var rawBytes = downloadUrl.GetBytesFromUrl(httpRes => ...);

这篇关于如何使用 ServiceStack 客户端使用文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆