当前位置: 动力学知识库 > 问答 > 编程问答 >

Silverlight is not liking my WCF MessageContract. Why?

问题描述:

I am attempting to upload a file through a Silverlight client using the following 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;

}

}

}

My problem is that the generated operation method on the client only takes a single argument; a byte array called FileByteStream. In other (non-Silverlight) clients I've created it asks for the MemberHeader fields as well. Without specifying these headers, the server has no idea what to do with the file. How can I set these headers when I call the operation?

Also, is there a better way to upload a file from a Silverlight client? This has been a huge headache.

Thanks.

网友答案:

The Silverlight subset of the WCF client does not support the [MessageHeader] attribute. You can still set message headers, but it's not as straightforward as in other platforms. Basically, you'll need to set the headers using the operation context, prior to making the call, like in the example below:

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);
}

Where contractNamespace is the XML namespace for the message header fields (IIRC they default to the same as the service contract). You can use Fiddler and something like the WCF Test Client to see which namespace is used there.

分享给朋友:
您可能感兴趣的文章:
随机阅读: