我正在尝试创建RESTful WCF服务,但它使用流式传输,因为它正在传输大型文件。 网上有很多例子,他们似乎最终都采用了一种方法。我无法让它发挥作用!
我创建了这个合约界面:
[ServiceContract(Namespace = "http://services.mydomain/MyService", ConfigurationName = "MyService")]
public interface IMyServiceContract
{
[OperationContract]
[WebGet]
Stream GetFile(string someValue, string filepath);
}
以下合同的实施:
public class MyServiceImpl : IMyServiceContract
{
public Stream GetFile(string someValue, string filepath)
{
DoSomethingWith(someValue);
return File.OpenRead(filepath);
}
}
最后我像这样创建WCF服务(我不能在app.config中放任何东西,因为它是动态启动的,所以一切都必须以编程方式启动而不依赖于app.config):
private void StartService()
{
MyServiceImpl svcImplementation = new MyServiceImpl();
ServiceHost host = new ServiceHost(svcImplementation, "http://localhost/MyService");
ServiceBehaviorAttribute behaviour = host.Description.Behaviors.Find<ServiceBehaviorAttribute>();
behaviour.InstanceContextMode = InstanceContextMode.Single;
WebHttpBinding binding = new WebHttpBinding
{
TransferMode = TransferMode.Streamed,
MaxReceivedMessageSize = int.MaxValue,
ReaderQuotas = { MaxArrayLength = int.MaxValue }
};
host.AddServiceEndpoint(typeof(IMyServiceContract), binding, "MyService")
.Behaviors.Add(new WebHttpBehavior());
ServiceMetadataBehavior smb = new ServiceMetadataBehavior
{
HttpGetEnabled = true
};
host.Description.Behaviors.Add(smb);
host.Open();
}
一切都在编译,一切都在没有任何错误的情况下开始。
当我在Postman中尝试访问http://localhost/MyService/GetFile?someValue=foo&filepath=C%3A%5Ctemp%5Csomefile.txt
时,我似乎得到了一个HTTP 405,它表示只允许POST(即使我用[WebGet]
如果我将Postman发送到POST而不是GET,我会收到HTTP 404。
如果我在浏览器中转到http://localhost/MyService
,我会获得标准的WCF服务页面,因此该服务肯定正在运行。
将UriTemplate
添加到[WebGet]
属性无效:
[OperationContract]
[WebGet(UriTemplate = "{someValue}/{filepath}")]
Stream GetFile(string someValue, string filepath);
根据我发现的例子,我觉得这应该很容易,但我必须遗漏一些必要的东西,因为我无法让它发挥作用。
我错过了什么?