3

我正在尝试使用以下内容通过 Silverlight 客户端上传文件MessageContract

[MessageContract]
public class CategoryClientFileTransferMC : IDisposable
{
    /// <summary>
    /// CategoryID - Category identity.
    /// </summary>
    [MessageHeader(MustUnderstand = true)]
    public int CategoryID;

    /// <summary>
    /// ID - File identifier.
    /// </summary>
    [MessageHeader(MustUnderstand = true)]
    public string ID;

    /// <summary>
    /// Length - File length in bytes.
    /// </summary>
    [MessageHeader(MustUnderstand = true)]
    public long Length;

    /// <summary>
    /// FileByteStream - File stream.
    /// </summary>
    [MessageBodyMember(Order = 1)]
    public Stream FileByteStream;

    /// <summary>
    /// Dispose the contract.
    /// </summary>
    public void Dispose()
    {
        if (FileByteStream != null)
        {
            FileByteStream.Close();
            FileByteStream = null;
        }
    }
}

我的问题是在客户端生成的操作方法只需要一个参数;一个字节数组,称为FileByteStream. 在我创建的其他(非 Silverlight)客户端中,它也要求输入MemberHeader字段。如果不指定这些标头,服务器将不知道如何处理该文件。调用操作时如何设置这些标头?

另外,有没有更好的方法从 Silverlight 客户端上传文件?这是一个巨大的头痛。

谢谢。

4

1 回答 1

3

WCF 客户端的 Silverlight 子集不支持该[MessageHeader]属性。您仍然可以设置消息头,但它不像其他平台那样简单。基本上,在进行调用之前,您需要使用操作上下文设置标头,如下例所示:

var client = new SilverlightReference1.MyClient();
using (new OperationContextScope(client.InnerChannel))
{
    string contractNamespace = "http://tempuri.org/";
    OperationContext.Current.OutgoingMessageHeaders.Add(
        MessageHeader.CreateHeader("CategoryId", contractNamespace, 1));
    OperationContext.Current.OutgoingMessageHeaders.Add(
        MessageHeader.CreateHeader("ID", contractNamespace, "abc123"));
    OperationContext.Current.OutgoingMessageHeaders.Add(
        MessageHeader.CreateHeader("Length", contractNamespace, 123456L));
    client.UploadFile(myFileContents);
}

contractNamespace消息头字段的 XML 命名空间在哪里(IIRC 它们默认与服务合同相同)。您可以使用 Fiddler 和 WCF 测试客户端之类的东西来查看那里使用了哪个命名空间。

于 2012-12-18T23:53:32.207 回答