我有一个基于Writing Highly Maintainable WCF Services的WCF服务。使用CommandService处理请求:
[WcfDispatchBehaviour]
[ServiceContract(Namespace="http://somewhere.co.nz/NapaWcfService/2013/11")]
[ServiceKnownType("GetKnownTypes")]
public class CommandService
{
[OperationContract]
public object Execute(dynamic command)
{
Type commandHandlerType = typeof(ICommandHandler<>).MakeGenericType(command.GetType());
dynamic commandHandler = BootStrapper.GetInstance(commandHandlerType);
commandHandler.Handle(command);
return command;
}
public static IEnumerable<Type> GetKnownTypes(ICustomAttributeProvider provider)
{
var coreAssembly = typeof(ICommandHandler<>).Assembly;
var commandTypes =
from type in coreAssembly.GetExportedTypes()
where type.Name.EndsWith("Command")
select type;
return commandTypes.ToArray();
}
}
一切都很好(感谢Steve),但现在我需要添加将文件上传到服务的功能。根据我的阅读并基于测试期间收到的错误,WCF在使用[MessageContract]
上传文件时需要使用Stream
。所以我装饰了我的命令类并将非Stream成员放入消息头中,并更新了我的绑定定义以使用流式传输:
[MessageContract]
public class AddScadaTileCommand
{
[MessageHeader(MustUnderstand = true)]
public int JobId { get; set; }
[MessageHeader(MustUnderstand = true)]
public string MimeType { get; set; }
[MessageHeader(MustUnderstand = true)]
public string Name { get; set; }
[MessageBodyMember(Order = 1)]
public Stream Content { get; set; }
}
不幸的是,当我使用要上传的文件调用该服务时,我收到错误:
尝试序列化参数时出错 http://somewhere.co.nz/NapaWcfService/2013/11:command。该 InnerException消息是带有数据的'Type'System.IO.FileStream' 合同名称 'FileStream:http://schemas.datacontract.org/2004/07/System.IO'不是 预期
所以我专门为文件上传请求添加了一个新方法:
[OperationContract]
public void Upload(AddScadaTileCommand addScadaTileCommand)
{
Type commandHandlerType = typeof(ICommandHandler<>).MakeGenericType(typeof(AddScadaTileCommand));
dynamic commandHandler = BootStrapper.GetInstance(commandHandlerType);
commandHandler.Handle(addScadaTileCommand);
}
这非常有效,除非我在方法定义中将AddScadaTileCommand
参数更改为dynamic
,在这种情况下,我得到与上面相同的错误。这似乎表明使用[MessageContract]
作为参数类型时未应用或忽略dynamic
属性。有没有办法解决这个问题,还是需要为涉及流的请求创建单独的方法?