将文件附加到 WCF REST 服务响应 [英] Attaching files to WCF REST service responses

查看:44
本文介绍了将文件附加到 WCF REST 服务响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的资源:

I have a resource that looks something like this:

/users/{id}/summary?format={format}

format 是xml"或json"时,我用一个用户摘要对象来响应,该对象由 WCF 自动编码 - 到目前为止还好.但是当 format 等于pdf"时,我希望我的响应包含一个简单的 HTTP 响应正文和一个 PDF 文件附件.

When format is "xml" or "json" I respond with a user summary object that gets automagically encoded by WCF - fine so far. But when format equals "pdf", I want my response to consist of a trivial HTTP response body and a PDF file attachment.

这是怎么做到的?对 WebOperationContext.Current.OutgoingResponse 进行黑客攻击似乎不起作用,即使这样做也不是正确的做法.在 CDATA 部分或响应中包含文件的位 不是安全.我应该创建一个 Message 的子类,然后提供一个响应它的自定义 IDispatchMessageFormatter 吗?我沿着这条路走了一小段路,但最终发现文档不透明.

How is this done? Hacking on WebOperationContext.Current.OutgoingResponse doesn't seem to work, and wouldn't be the right thing even if it did. Including the bits of the file in a CDATA section or something in the response isn't safe. Should I create a subclass of Message, then provide a custom IDispatchMessageFormatter that responds with it? I went a short distance down that path but ultimately found the documentation opaque.

什么是正确的?

推荐答案

原来我需要的是 WCF raw";模式,如此处.从广义上讲,我想这样做:

It turns out that what I need is WCF "raw" mode, as described here. Broadly speaking, I want to do this:

[OperationContract, WebGet(UriTemplate = "/users/{id}/summary?format={format}"]
public Stream GetUserSummary(string id, string format)
{
    if(format == "pdf")
    {
        WebOperationContext.Current.OutgoingResponse.ContentType = "application/pdf";
        return new MemoryStream(CreatePdfSummaryFileForUser(id));
    }
    else
    {
        // XML or JSON serialization.  I can't figure out a way to not do this explicitly, but my use case involved custom formatters anyway so I don't care.
    }
}

这篇关于将文件附加到 WCF REST 服务响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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