I do it this way and it works.
Add factory class to web service
My interface:
public interface IService1 { [OperationContract] [WebInvoke(BodyStyle = WebMessageBodyStyle.WrappedRequest, Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "UploadFile/{fileName}")] void UploadFile(string fileName, Stream fileContent); }
My method:
public void UploadFile(string fileName, Stream fileContent) { var pathfile = "\\\\SERVER\\TravelsRequestFiles"; using (var fileStream = new FileStream(string.Concat(pathfile, "\\", fileName), FileMode.Create, FileAccess.Write)) { fileContent.CopyTo(fileStream); } }
my FactoryClass:
public class ServiceFactory : ServiceHostFactory { protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses) { return new MyServiceHost(serviceType, baseAddresses); } class MyServiceHost : ServiceHost { public MyServiceHost(Type serviceType, Uri[] baseAddresses) : base(serviceType, baseAddresses) { } protected override void InitializeRuntime() { ServiceEndpoint endpoint = this.Description.Endpoints[0]; endpoint.Behaviors.Add(new EndpointBehaviors()); base.InitializeRuntime(); } } }
I added the EndpointBehaviors class for which it finds the UploadFile operation and removes its DataContractSerializerOperationBehavior , and then it works!
public class EndpointBehaviors: IEndpointBehavior { public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) { ContractDescription cd = endpoint.Contract; foreach (DispatchOperation objDispatchOperation in endpointDispatcher.DispatchRuntime.Operations) { if (objDispatchOperation.Name.Equals("UploadFile")) { OperationDescription myOperationDescription = cd.Operations.Find("UploadFile"); DataContractSerializerOperationBehavior serializerBehavior = myOperationDescription.Behaviors.Find<DataContractSerializerOperationBehavior>(); myOperationDescription.Behaviors.Remove(serializerBehavior); } } } public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) { } public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters) { } public void Validate(ServiceEndpoint endpoint) { BindingElementCollection elements = endpoint.Binding.CreateBindingElements(); WebMessageEncodingBindingElement webEncoder = elements.Find<WebMessageEncodingBindingElement>(); if (webEncoder == null) { throw new InvalidOperationException("This behavior must be used in an endpoint with the WebHttpBinding (or a custom binding with the WebMessageEncodingBindingElement)."); } } }
jst
source share