I have read many articles here on SO, and on MSDN and Code Project. And still the answer eludes me.
I have created a WCF service that has a callback contract, and a Windows Forms app (test harness) that implements the callback interface.
Here are the interfaces:
[ServiceContract]
public interface ICacheService
{
[OperationContract]
bool AddToCache(string type, string key, string source, object item, int duration);
[OperationContract]
bool Remove(string key);
}
[ServiceContract(SessionMode=SessionMode.Required, CallbackContract=typeof(ISearchCallback))]
public interface ICacheSearch
{
[OperationContract(IsOneWay=true)]
void SearchCache(string source);
}
public interface ISearchCallback
{
[OperationContract(IsOneWay=true)]
void OnCallback(object data);
}
My service (left out the Add and Remove to conserve space - they work as expected):
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode=ConcurrencyMode.Multiple)]
public class CachingService : ICacheService, ICacheSearch, IDisposable
{
private List<ICache> _cacheList = new List<ICache>();
private ISearchCallback _callback = null;
public void SearchCache(string source)
{
try
{
_callback = OperationContext.Current.GetCallbackChannel<ISearchCallback>();
List<object> items = new List<object>();
foreach (ICache cache in this._cacheList)
{
foreach (CacheItem item in cache.GetCacheItemsBySource(source))
{
items.Add(item.Value);
}
}
ReadOnlyCollection<object> outList = new ReadOnlyCollection<object>(items);
_callback.OnCallback(outList);
}
catch { }
}
}
My service is hosted in a Windows Service. Here is the system.serviceModel section from app.config:
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding
name="WSHttpBinding_ICacheService"
closeTimeout="00:01:00"
openTimeout="00:01:00"
receiveTimeout="00:01:00"
sendTimeout="00:01:00"
maxBufferPoolSize="2147483647"
maxReceivedMessageSize="2147483647">
<readerQuotas maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxDepth="2147483647" maxNameTableCharCount="2147483647" maxStringContentLength="2147483647"/>
</binding>
</wsHttpBinding>
<wsDualHttpBinding>
<binding
name="WSDualHttpBinding_ICacheSearch"
closeTimeout="00:01:00"
openTimeout="00:01:00"
receiveTimeout="00:01:00"
sendTimeout="00:01:00"
maxBufferPoolSize="2147483647"
maxReceivedMessageSize="2147483647"
clientBaseAddress="http://localhost:5057/wsDualHttpBinding"
useDefaultWebProxy="true"
transactionFlow="false">
<readerQuotas maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxDepth="2147483647" maxNameTableCharCount="2147483647" maxStringContentLength="2147483647"/>
</binding>
</wsDualHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="CacheService.CachingService">
<host>
<baseAddresses>
<add baseAddress="http://localhost:5055/CachingService/"/>
</baseAddresses>
</host>
<endpoint address="Search" binding="wsDualHttpBinding" contract="CacheService.ICacheSearch" />
<endpoint address="" binding="wsHttpBinding" contract="CacheService.ICacheService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<client>
<endpoint address="http://localhost:5055/CachingService/Search" binding="wsDualHttpBinding"
bindingConfiguration="WSDualHttpBinding_ICacheSearch" contract="CacheService.ICacheSearch"
name="WSDualHttpBinding_ICacheSearch" />
<endpoint address="http://localhost:5055/CachingService" binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_ICacheService" contract="CacheService.ICacheService"
name="WSHttpBinding_ICacheService" />
</client>
</system.serviceModel>
Finally, I created a simple Windows Forms app to test. It is declared as:
[CallbackBehavior(UseSynchronizationContext = false, ConcurrencyMode = ConcurrencyMode.Single)]
public partial class Form1 : Form, cacheService.ICacheSearchCallback
{
InstanceContext context = null;
cacheService.CacheServiceClient _service = null;
cacheService.CacheSearchClient _proxy = null;
private void Form1_Load(object sender, EventArgs e)
{
_syncContext = System.Threading.SynchronizationContext.Current;
_service = new cacheService.CacheServiceClient();
this.dataGridView1.AutoGenerateColumns = true;
context = new InstanceContext(this);
_proxy = new cacheService.CacheSearchClient(context);
RefreshList();
}
private void RefreshList()
{
_proxy.SearchCache("mySource");
}
public void OnCallback(object data)
{
this._data = data;
this.dataGridView1.DataSource = this._data;
}
The call to the service (_proxy.SearchCache("mySource")) successfully executes the method on the service and service calls _callback.OnCallback(outList). But the callback method implemented in my test app is never called and so the data are never conveyed to the test app.
Again, I have looked at every recent WCF article on SO and many other blogs and code sites. I feel like I need a another pair of eyes to point out the obvious so I can get back to work.
Many thanks,
Robert
Related
I have WCF service with DataContract json serialization. I would like to add service endpoints to consume Protobuf data messages.
I tried to use nugget package ProtoBuf.Services.WCF.
Added endpoint via web.config configuration. However, every request on protobuf endpoint with address "proto" returns 400 Bad request. Web.config sample is written bellow. Endpoint with default address "" works properly.
Get method:
HTTP 200 OK http://localhost:65460/BeaconService.svc/GetData
HTTP 400 BAD REQUEST: http://localhost:65460/BeaconService.svc/proto/GetData
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding transferMode="Streamed">
<security mode="None" />
</binding>
</webHttpBinding>
<basicHttpBinding>
<binding messageEncoding="Mtom">
<security mode="None" />
</binding>
</basicHttpBinding>
</bindings>
<extensions>
<behaviorExtensions>
<add name="protobuf" type="ProtoBuf.ServiceModel.ProtoBehaviorExtension, protobuf-net" />
</behaviorExtensions>
</extensions>
<services>
<service behaviorConfiguration="DefaultServiceBehavior" name="Services.BeaconService">
<endpoint address="" behaviorConfiguration="httpBehavior" binding="webHttpBinding" contract="Services.IBeaconService" />
<endpoint address="proto" behaviorConfiguration="protoBehavior" binding="basicHttpBinding" contract="Services.IBeaconService" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="protoBehavior">
<protobuf />
</behavior>
<behavior name="httpBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
</system.serviceModel>
Please, which part of configuration is defective. Eventualy, what is proper way to call Get method on "proto" WCF endpoint to avoid HTTP 400 Bad request message?
Unfortunately, I have failed to implement ProtoBuf.Services.WCF and decided to use another approach. In general, WCF by default uses DataContractSerializer.
After reading this article, I realized It is possible to replace this serializer with another one, f.e. protobuf serializer in this library. So I created behavior extension, which replaces DataContractSerializer with my custom ProtobufSerializer. In configuration added another endpoint, which has set behavior extension to use my custom ProtobufSerializer.
WebHttpBehavior:
public class ProtobufBehavior : WebHttpBehavior
{
protected override IDispatchMessageFormatter GetRequestDispatchFormatter(OperationDescription operationDescription, ServiceEndpoint endpoint)
{
return new ProtobufDispatchFormatter(operationDescription);
}
protected override IDispatchMessageFormatter GetReplyDispatchFormatter(OperationDescription operationDescription, ServiceEndpoint endpoint)
{
return new ProtobufDispatchFormatter(operationDescription);
}
}
Dispatch formatter:
namespace Services.Extension.ProtobufSerializationExtension
{
public class ProtobufDispatchFormatter : IDispatchMessageFormatter
{
OperationDescription operation;
bool isVoidInput;
bool isVoidOutput;
public ProtobufDispatchFormatter(OperationDescription operation)
{
this.operation = operation;
this.isVoidInput = operation.Messages[0].Body.Parts.Count == 0;
this.isVoidOutput = operation.Messages.Count == 1 || operation.Messages[1].Body.ReturnValue.Type == typeof(void);
}
public void DeserializeRequest(Message message, object[] parameters)
{
if (!message.IsEmpty)
{
XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents();
bodyReader.ReadStartElement("Binary");
byte[] rawBody = bodyReader.ReadContentAsBase64();
MemoryStream ms = new MemoryStream(rawBody);
using (StreamReader sr = new StreamReader(ms))
for (int i = 0; i < parameters.Length; i++)
parameters[i] = Serializer.Deserialize(operation.Messages[i].Body.Parts[i].Type, sr.BaseStream);
}
}
public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
{
byte[] body;
using (MemoryStream ms = new MemoryStream())
using (StreamWriter sw = new StreamWriter(ms))
{
Serializer.Serialize(sw.BaseStream, result);
sw.Flush();
body = ms.ToArray();
}
Message replyMessage = Message.CreateMessage(messageVersion, operation.Messages[1].Action, new RawBodyWriter(body));
replyMessage.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Raw));
return replyMessage;
}
class RawBodyWriter : BodyWriter
{
internal static readonly byte[] EmptyByteArray = new byte[0];
byte[] content;
public RawBodyWriter(byte[] content)
: base(true)
{
this.content = content;
}
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
writer.WriteStartElement("Binary");
writer.WriteBase64(content, 0, content.Length);
writer.WriteEndElement();
}
}
}
}
Extension element:
namespace Services.Extension.ProtobufSerializationExtension
{
public class ProtobufSerializationServiceElement : BehaviorExtensionElement
{
public override Type BehaviorType
{
get { return typeof(ProtobufBehavior); }
}
protected override object CreateBehavior()
{
return new ProtobufBehavior();
}
}
}
Web config:
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding transferMode="Streamed">
<security mode="None" />
</binding>
</webHttpBinding>
</bindings>
<extensions>
<behaviorExtensions>
<add name="protobufExtension" type="Services.Extension.ProtobufSerializationExtension.ProtobufSerializationServiceElement, Services" />
</behaviorExtensions>
</extensions>
<services>
<service behaviorConfiguration="DefaultServiceBehavior" name="Services.BeaconService">
<endpoint address="" behaviorConfiguration="httpBehavior" binding="webHttpBinding" contract="Services.IBeaconService" />
<endpoint address="proto" behaviorConfiguration="protoBehavior" binding="webHttpBinding" contract="Services.IBeaconService" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="protoBehavior">
<webHttp/>
<protobufExtension/>
</behavior>
<behavior name="httpBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
</system.serviceModel>
Services.Extension.ProtobufSerializationExtension is name of my custom namespace inside application structure. Hope this helps someone.
I need to write WCF service using TLS 1.2.I need to use only this security protocol and (as i think) refuse connections with other secure protocol types. I have created certificate. Bind it to port. Https works well. I read everywhere that i need to write next string of code:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Ok, i wrote it, but had no effect. Service side code:
using System;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Net;
using System.ServiceModel;
using System.Runtime.Serialization;
using static System.Console;
namespace ConsoleHost
{
public class DistributorValidator : UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
throw new SecurityTokenException("Both username and password required");
if (userName != "login" || password != "pass")
throw new FaultException($"Wrong username ({userName}) or password ");
}
}
public class Service1 : IService1
{
public string GetData(int value)
{
return $"You entered: {value}";
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException(nameof(composite));
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
}
[DataContract]
public class CompositeType
{
[DataMember]
public bool BoolValue { get; set; } = true;
[DataMember]
public string StringValue { get; set; } = "Hello ";
}
class Program
{
static void Main(string[] args)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServiceHost host = new ServiceHost(typeof(Service1));
host.Open();
WriteLine("Press any key to stop server...");
ReadLine();
}
}
}
App.config contains:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<system.serviceModel>
<services>
<service name="ConsoleHost.Service1">
<host>
<baseAddresses>
<add baseAddress = "https://localhost:8734/Service1/" />
</baseAddresses>
</host>
<endpoint address="" binding="wsHttpBinding" contract="ConsoleHost.IService1" bindingConfiguration="securityBinding">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/>
</service>
</services>
<bindings>
<wsHttpBinding>
<binding name="securityBinding">
<security mode="TransportWithMessageCredential">
<transport clientCredentialType="None" />
<message clientCredentialType="UserName" />
<!--establishSecurityContext="false" />-->
</security>
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="True" httpsGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="False" />
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="ConsoleHost.DistributorValidator,ConsoleHost"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
Client side code:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
Service1Client client = new Service1Client();
client.ClientCredentials.UserName.UserName = "login";
client.ClientCredentials.UserName.Password = "pass";
Console.WriteLine(client.GetData(10));
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
if (ex.InnerException != null)
{
Console.WriteLine("Inner: " + ex.InnerException.Message);
if (ex.InnerException.InnerException != null)
Console.WriteLine("Inner: " + ex.InnerException.InnerException.Message);
}
}
Console.ReadLine();
}
}
}
As you can see on service side i have set security protocol to Tls 1.2. On client side i have set security protocol to Ssl3. I am waiting that service will refuse client connection, because server must work and accept clients who will work with only Tls 1.2 security protocol. But i'm not getting this result. Client connects and works well. What's the problem?
I understand that i can change some settings on IIS to use only Tls 1.2. But i am making self hosting wcf service and that's the problem.
It can't be done for server using ServicePointManager.SecurityProtocol option, that's used to connection to sth through a specific security protocol. You can't turn off some security protocol for an separate application, you able to allow or dissallow connections for whole server. If u want disable all protocols except TLS 1.2 u have to open registry windows and find out the next key:
HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\
And set the next values for each protocol in key [Server]: DisabledByDefault = 1, Enabled = 0
How to enable TLS
I was actually following this article
https://social.msdn.microsoft.com/Forums/vstudio/en-US/87a254c8-e9d1-4d4c-8f62-54eae497423f/how-to-ssl-passthrough-from-bigip?forum=wcf
I have complete step 1 and 2 but after implement custom binding that was discuss in step 3 I got following error
The Scheme cannot be computed for this binding because this CustomBinding lacks a TransportBindingElement. Every binding must have at least one binding element that derives from TransportBindingElement.
My Code for Custom Binding is as follows:
public class MyCustomBinding : Binding
{
private HttpTransportBindingElement transport;
private BinaryMessageEncodingBindingElement encoding;
public MyCustomBinding()
: base()
{
this.InitializeValue();
}
public override BindingElementCollection CreateBindingElements()
{
BindingElementCollection elements = new BindingElementCollection();
elements.Add(this.encoding);
elements.Add(this.transport);
return elements;
}
public override string Scheme
{
get { return this.transport.Scheme; }
}
private void InitializeValue()
{
this.transport = new HttpTransportBindingElement();
this.encoding = new BinaryMessageEncodingBindingElement();
}
}
public class MyCustomBindingCollectionElement : BindingCollectionElement
{
// type of custom binding class
public override Type BindingType
{
get { return typeof(MyCustomBinding); }
}
// override ConfiguredBindings
public override ReadOnlyCollection<IBindingConfigurationElement> ConfiguredBindings
{
get
{
return new ReadOnlyCollection<IBindingConfigurationElement>(
new List<IBindingConfigurationElement>());
}
}
// return Binding class object
protected override Binding GetDefault()
{
return new MyCustomBinding();
}
public override bool ContainsKey(string name) {
return true;
}
protected override bool TryAdd(string name, Binding binding, Configuration config)
{
return true;
}
}
and my web.Config is as follows:
<bindings>
<customBinding>
<binding name="MyCustomBinding">
<binaryMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16"
maxSessionSize="2048">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
</binaryMessageEncoding>
<textMessageEncoding
messageVersion="Soap11WSAddressingAugust2004"/>
<httpsTransport manualAddressing="false" maxBufferPoolSize="524288"
maxReceivedMessageSize="65536" allowCookies="false" authenticationScheme="Anonymous"
bypassProxyOnLocal="false" decompressionEnabled="true" hostNameComparisonMode="StrongWildcard"
keepAliveEnabled="true" maxBufferSize="65536" proxyAuthenticationScheme="Anonymous"
realm="" transferMode="Buffered" unsafeConnectionNtlmAuthentication="false" useDefaultWebProxy="true"/>
</binding>
</customBinding>
</bindings>
<services>
<service name="ADHA.ADHAServiceApi" >
<endpoint address="" binding="customBinding" bindingConfiguration="MyCustomBinding" contract="ADHA.IADHAService">
</endpoint>
<endpoint address="mex" binding="customBinding" contract="IMetadataExchange" />
</service>
</services>
<extensions>
<bindingExtensions>
<!--<add name="ProxyElement" type="ADHA.Model.HttpTransportBindingElementProxy, ADHA"/>-->
<add name="MyCustomBinding" type="ADHA.Model.MyCustomBindingCollectionElement,ADHA,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</bindingExtensions>
</extensions>
Here i am implementing custom usernamepasswordvalidator in WCF RESTfull service.What i need is while invoking this one http://localhost:12229/RestServiceImpl.svc/GetStudentObj through Chrome REST Client it is not validating the username password..it directly invoke this method and fetching the result.What am i doing wrong here??
My interface
[ServiceContract]
public interface IRestServiceImpl
{
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "/GetStudentObj", RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
Student GetStudent();
}
SVC
public class RestServiceImpl : IRestServiceImpl
{
public Student GetStudent()
{
Student stdObj = new Student
{
StudentName = "Foo",
Age = 29,
Mark = 95
};
return stdObj;
}
public class CustomUserNameValidator : UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
if (null == userName || null == password)
{
throw new ArgumentNullException("You must provide both the username and password to access this service");
}
if (!(userName == "user1" && password == "test") && !(userName == "user2" && password == "test"))
{
throw new SecurityTokenException("Unknown Username or Incorrect Password");
}
}
}
}
and Web.Config
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="webHttpTransportSecurity">
<security mode="Transport">
<transport clientCredentialType="Basic"></transport>
</security>
</binding>
</webHttpBinding>
</bindings>
<protocolMapping>
<add scheme="http" binding="webHttpBinding"/>
</protocolMapping>
<services>
<service name="RestService.RestServiceImpl" >
<endpoint address="" binding="webHttpBinding" contract="RestService.IRestServiceImpl"></endpoint>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior>
<webHttp />
</behavior >
</endpointBehaviors>
<serviceBehaviors>
<behavior name="SecureRESTSvcTestBehavior">
<serviceMetadata httpGetEnabled="false" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="RESTfulSecuritySH.CustomUserNameValidator, RESTfulSecuritySH" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
Any suggestion??
It seems that you didn't set the custom behavior for your service.
You need to tell the service about your SecureRESTSvcTestBehavior behavior by using the behaviorConfiguration attribute:
<service name="RestService.RestServiceImpl" behaviorConfiguration="SecureRESTSvcTestBehavior">
<endpoint address="" binding="webHttpBinding" contract="RestService.IRestServiceImpl"></endpoint>
</service>
I've created a simple RESTful WCF file streaming service. When an error occurs, I would like a 500 Interal Server Error response code to be generated. Instead, only 400 Bad Requests are generated.
When the request is valid, I get the proper response (200 OK), but even if I throw an Exception I get a 400.
IFileService:
[ServiceContract]
public interface IFileService
{
[OperationContract]
[WebInvoke(Method = "GET",
BodyStyle = WebMessageBodyStyle.Bare,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/DownloadConfig")]
Stream Download();
}
FileService:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class GCConfigFileService : IGCConfigFileService
{
public Stream Download()
{
throw new Exception();
}
}
Web.Config
<location path="FileService.svc">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
<system.serviceModel>
<client />
<behaviors>
<serviceBehaviors>
<behavior name="FileServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
<services>
<service name="FileService"
behaviorConfiguration="FileServiceBehavior">
<endpoint address=""
binding="webHttpBinding"
bindingConfiguration="FileServiceBinding"
behaviorConfiguration="web"
contract="IFileService"></endpoint>
</service>
</services>
<bindings>
<webHttpBinding>
<binding
name="FileServiceBinding"
maxBufferSize="2147483647"
maxReceivedMessageSize="2147483647"
transferMode="Streamed"
openTimeout="04:01:00"
receiveTimeout="04:10:00"
sendTimeout="04:01:00">
<readerQuotas maxDepth="2147483647"
maxStringContentLength="2147483647"
maxArrayLength="2147483647"
maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647" />
</binding>
</webHttpBinding>
</bindings>
SIMPLE:
Try out throw new WebFaultException(HttpStatusCode.InternalServerError);
To specify an error details:
throw new WebFaultException<string>("Custom Error Message!", HttpStatusCode.InternalServerError);
ADVANCED:
If you want better exception handling with defining HTTP status for each exception you'll need to create a custom ErrorHandler class for example:
class HttpErrorHandler : IErrorHandler
{
public bool HandleError(Exception error)
{
return false;
}
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
if (fault != null)
{
HttpResponseMessageProperty properties = new HttpResponseMessageProperty();
properties.StatusCode = HttpStatusCode.InternalServerError;
fault.Properties.Add(HttpResponseMessageProperty.Name, properties);
}
}
}
Then you need to create a service behaviour to attach to your service:
class ErrorBehaviorAttribute : Attribute, IServiceBehavior
{
Type errorHandlerType;
public ErrorBehaviorAttribute(Type errorHandlerType)
{
this.errorHandlerType = errorHandlerType;
}
public void Validate(ServiceDescription description, ServiceHostBase serviceHostBase)
{
}
public void AddBindingParameters(ServiceDescription description, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection parameters)
{
}
public void ApplyDispatchBehavior(ServiceDescription description, ServiceHostBase serviceHostBase)
{
IErrorHandler errorHandler;
errorHandler = (IErrorHandler)Activator.CreateInstance(errorHandlerType);
foreach (ChannelDispatcherBase channelDispatcherBase in serviceHostBase.ChannelDispatchers)
{
ChannelDispatcher channelDispatcher = channelDispatcherBase as ChannelDispatcher;
channelDispatcher.ErrorHandlers.Add(errorHandler);
}
}
}
Attaching to behaviour:
[ServiceContract]
public interface IService
{
[OperationContract(Action = "*", ReplyAction = "*")]
Message Action(Message m);
}
[ErrorBehavior(typeof(HttpErrorHandler))]
public class Service : IService
{
public Message Action(Message m)
{
throw new FaultException("!");
}
}