Trying to make simple selfhosted WCF service in console application:
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
namespace SupportSrvWCF
{
[ServiceContract]
public interface IA
{
[OperationContract]
int LogIt(int id, string data, ref int level);
}
public class SupportServicee : IA
{
public int LogIt(int id, string data, ref int level)
{
return 0;
}
}
class Program
{
static void Main(string[] args)
{
try
{
ServiceHost selfHost = new ServiceHost(typeof(SupportServicee));
selfHost.Open();
Console.WriteLine("The service is running. Press any key to stop.");
Console.ReadKey();
}
catch (Exception e)
{
Console.WriteLine("An error occurred: '{0}'", e);
}
}
}
}
App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<system.serviceModel>
<services>
<service name="SupportSrvWCF.SupportServicee">
<endpoint address="" binding="basicHttpBinding" contract="SupportSrvWCF.IA ">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8002/WCFService1" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<!--<behavior name="CalculatorServiceBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>-->
<behavior name="">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
</system.serviceModel>
</configuration>
Have exception:
An error occurred: 'System.InvalidOperationException: The contract name 'Support
SrvWCF.IA ' could not be found in the list of contracts implemented by the servi
ce 'SupportServicee'.
Where is problem
hello try the following code instead and delete the service configuration from app.config
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
namespace SupportSrvWCF
{
[ServiceContract]
public interface IA
{
[OperationContract]
int LogIt(int id, string data, ref int level);
}
public class SupportServicee : IA
{
public int LogIt(int id, string data, ref int level)
{
return 0;
}
}
class Program
{
static void Main(string[] args)
{
using (ServiceHost selfHost = new ServiceHost(typeof(SupportServicee),new Uri("http://localhost:8080/Myservice")))
{
try
{
selfHost.AddServiceEndpoint(typeof(IA),new BasicHttpBinding(),"basic");
selfHost.Open();
Console.WriteLine("The service is running. Press any key to stop.");
Console.ReadKey();
}
catch (Exception e)
{
Console.WriteLine("An error occurred: '{0}'", e);
}
}
}
}
}
Related
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 am getting an error when the client reference is used a second time for calling the underlying method. On first call, It works perfectly. I have googled it and did so many tries like setting timeouts but nothing worked. Any suggestions will be highly appreciated. Also, if more details are required please let me know, I will post the required code.
A MDI Child form will call this method.
Debugger shows CommunicationException.
Trace Viewer shows message: The operation cannot be completed because the pipe was closed. This may have been caused by the application on the other end of the pipe exiting.
Contract
[ServiceContract(Namespace = "http://Company/ManagementInformationSystemServices/", SessionMode = SessionMode.Required)]
public interface IPrincipalService
{
#region Service contracts for Reports
[OperationContract]
[FaultContract(typeof(ProcessExecutionFault))]
Parcel InsertParcel(Parcel singleParcel, out bool Exists);
[OperationContract]
[FaultContract(typeof(ProcessExecutionFault))]
Parcel GetByParcelId(int id);
#endregion
}
Contract Implementation
[ServiceBehavior(UseSynchronizationContext = false, ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.Single)]
public class PrincipalService : IPrincipalService
{
#region Constructor
public PrincipalService()
{
}
#endregion
#region Public Methods
#region Parcel Methods
public Parcel InsertParcel(Parcel singleParcel, out bool Exists)
{
bool ExistsInner = false;
try
{
ParcelComponent parcelComponent = new ParcelComponent();
singleParcel = parcelComponent.Insert(singleParcel, out ExistsInner);
Exists = ExistsInner;
return singleParcel;
}
catch (Exception ex)
{
throw new FaultException<ProcessExecutionFault>
(new ProcessExecutionFault(LogResource.InsertParcelExistsError, ex), ex.Message);
}
}
public Parcel GetByParcelId(int id)
{
try
{
ParcelComponent parcelComponent = new ParcelComponent();
return parcelComponent.GetById(id);
}
catch (Exception ex)
{
throw new FaultException<ProcessExecutionFault>
(new ProcessExecutionFault(LogResource.ReadParcelError, ex), ex.Message);
}
}
#endregion
#endregion
}
Server Configuration
<system.serviceModel>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
<services>
<service behaviorConfiguration="serviceBehavior" name="ManagementInformationSystem.Services.PrincipalService">
<host>
<baseAddresses>
<add baseAddress="net.pipe://localhost/ManagementInformationSystemServices" />
</baseAddresses>
</host>
<endpoint address="PrincipalService"
binding="netNamedPipeBinding"
contract="ManagementInformationSystem.Services.Contracts.IPrincipalService" />
<endpoint address="PrincipalService/mex"
binding="mexNamedPipeBinding"
contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="serviceBehavior">
<serviceMetadata httpGetEnabled="false" />
<serviceDebug includeExceptionDetailInFaults="true" />
<dataContractSerializer maxItemsInObjectGraph="2147483647"/>
</behavior>
</serviceBehaviors>
</behaviors>
<diagnostics wmiProviderEnabled="true">
</diagnostics>
Client Configuration
<system.serviceModel>
<bindings>
<netNamedPipeBinding>
<binding name="NetNamedPipeBinding_IPrincipalService" />
</netNamedPipeBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="endpointBehavior">
<dataContractSerializer maxItemsInObjectGraph="2147483647"/>
</behavior>
</endpointBehaviors>
</behaviors>
<client>
<endpoint address="net.pipe://localhost/ManagementInformationSystemServices/PrincipalService"
binding="netNamedPipeBinding" bindingConfiguration="NetNamedPipeBinding_IPrincipalService"
contract="PrincipalServiceReference.IPrincipalService" name="NetNamedPipeBinding_IPrincipalService">
<identity>
<userPrincipalName value="company-238\company" />
</identity>
</endpoint>
</client>
<diagnostics wmiProviderEnabled="true">
</diagnostics>
Service Helper Class and I am getting Communication Exception here
public static class ServiceHelper<T>
{
public static ChannelFactory<T> _channelFactory = new ChannelFactory<T>(GlobalResource.PrincipalServiceEndPointName);
public static void Use(UseServiceDelegate<T> codeBlock)
{
IClientChannel proxy = (IClientChannel)_channelFactory.CreateChannel();
bool success = false;
try
{
codeBlock((T)proxy);
proxy.Close();
success = true;
}
catch (CommunicationException ex)
{
throw ex;
}
catch (TimeoutException ex)
{
throw ex;
}
finally
{
if (!success)
{
proxy.Abort();
}
}
}
}
I have a WCF service library hosted by a windows service. I am using Castle Windson to do constructor injection. When I try to start up the service I get an exception with the following inner exception:
{"A registration already exists for URI 'net.tcp://localhost:8056/LoggingServiceWCF/tcp'."}
App.config:
<system.serviceModel>
<services>
<service name="LoggingServiceWCF.LoggingService">
<endpoint address="tcp" binding="netTcpBinding" bindingConfiguration="" name="netTcp" contract="LoggingServiceWCF.ILoggingService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="tcpMex" binding="mexTcpBinding" bindingConfiguration="" name="mexTcp" contract="IMetadataExchange" />
<endpoint address="pipe" binding="netNamedPipeBinding" bindingConfiguration="" name="namedPipe" contract="LoggingServiceWCF.ILoggingService" />
<endpoint address="pipeMex" binding="mexNamedPipeBinding" contract="IMetadataExchange" bindingConfiguration="" name="mexPipe" />
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:8056/LoggingServiceWCF" />
<add baseAddress="net.pipe://localhost/LoggingServiceWCF"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="false" httpsGetEnabled="false" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
Castle windsor installer:
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.AddFacility<WcfFacility>();
container.Register(Component
.For<LoggerServiceCore.Interfaces.ILogger>()
.ImplementedBy<LogManager>(),
Component
.For<ILoggingService>()
.ImplementedBy<LoggingService>()
.LifeStyle.Transient
.AsWcfService());
container.Register(Component
.For<ServiceBase>()
.ImplementedBy<LoggingHostService>());
}
Program.cs:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
#if DEBUG
Debugger.Launch();
#endif
ServiceBase.Run(CreateContainer().Resolve<ServiceBase>());
}
private static IWindsorContainer CreateContainer()
{
var container = new WindsorContainer();
container.Install(FromAssembly.This());
return container;
}
}
Windows service class:
public partial class LoggingHostService : ServiceBase
{
internal static ServiceHost service = null;
public LoggingHostService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
if(service != null)
{
service.Close();
}
service = new ServiceHost(typeof(LoggingServiceWCF.LoggingService));
service.Open();
}
protected override void OnStop()
{
if(service != null)
{
service.Close();
service = null;
}
}
}
I have Googled around and found all kinds of solutions to similar issues, but I can't seem to find something that works in my case.
I have a WebService that intents to upload a file to a server but i keep getting the error in the title when i want to run it from my VS2010.
I have searched over this site and the solutions have not helped me, unless i'm doing something wrong.
this is the site that i get the example: Example
here is my Interface
namespace FUWcf
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
public class FileUploadService : IFileUploadService
{
public bool UploadFileData(FileData fileData)
{
bool result = false;
try
{
//Set the location where you want to save your file
string FilePath = Path.Combine(ConfigurationManager.AppSettings["Path"], fileData.FileName);
//If fileposition sent as 0 then create an empty file
if (fileData.FilePosition == 0)
{
File.Create(FilePath).Close();
}
//Open the created file to write the buffer data starting at the given file position
using (FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
{
fileStream.Seek(fileData.FilePosition, SeekOrigin.Begin);
fileStream.Write(fileData.BufferData, 0, fileData.BufferData.Length);
}
}
catch (Exception ex)
{
ErrorDetails ed = new ErrorDetails();
ed.ErrorCode = 1001;
ed.ErrorMessage = ex.Message;
throw new FaultException<ErrorDetails>(ed);
}
return result;
}
}
}
Here is the service:
namespace FUWcf
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface IFileUploadService
{
[OperationContract]
[FaultContract(typeof(ErrorDetails))]
bool UploadFileData(FileData fileData);
}
[DataContract]
public class FileData
{
[DataMember]
public string FileName { get; set; }
[DataMember]
public byte[] BufferData { get; set; }
[DataMember]
public int FilePosition { get; set; }
}
[DataContract]
public class ErrorDetails
{
[DataMember]
public int ErrorCode { get; set; }
[DataMember]
public string ErrorMessage { get; set; }
}
}
And here is my web.config
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<appSettings>
<add key="Path" value="C:\Users\c.asacha\Documents\Proyectos\Generales\FUWcf\FUWcf\temp\"/>
</appSettings>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHBBinding" />
</wsHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="fus" name="FUWcd.FileUploadService">
<endpoint address=""
binding="wsHttpBinding" bindingConfiguration="WSHBBinding" name="FileUploadService"
contract="FUWcf.IFileUploadService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="fus">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="false" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
I hope someone can help me with this, or a link for a better example.
Thanks in advance.
You configuration is wrong ( Service name is name="FUWcd.FileUploadService" where it should be name="FUWcf.FileUploadService")
Anyway- Created the web site and added the web service like this ( You dont need Mex endpoint in web configuration as it is already on, The url will become the servicename http://{localServerName}:{port}/FileUploadService.svc):
public class FileUploadService : IFileUploadService
{
public bool UploadFileData(FileData fileData)
{
bool result = false;
try
{
//Set the location where you want to save your file
string FilePath = Path.Combine(ConfigurationManager.AppSettings["Path"], fileData.FileName);
//If fileposition sent as 0 then create an empty file
if (fileData.FilePosition == 0)
{
File.Create(FilePath).Close();
}
//Open the created file to write the buffer data starting at the given file position
using (FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
{
fileStream.Seek(fileData.FilePosition, SeekOrigin.Begin);
fileStream.Write(fileData.BufferData, 0, fileData.BufferData.Length);
}
}
catch (Exception ex)
{
ErrorDetails ed = new ErrorDetails();
ed.ErrorCode = 1001;
ed.ErrorMessage = ex.Message;
throw new FaultException<ErrorDetails>(ed);
}
return result;
}
}
Data Contracts were same as well.
Then in Web.Config file added like this and it works fine:
<system.serviceModel>
<services>
<service name="WebApplication1.FileUploadService">
<endpoint address="fileService" binding="wsHttpBinding" bindingConfiguration=""
contract="WebApplication1.IFileUploadService" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
Hello i've tried to get the Ierrorhandler to work now for hours and im pretty stuck :)
i've gotten the most results out of this guide
http://www.remondo.net/wcf-global-exception-handling-attribute-and-ierrorhandler/#comment-10385
but i cant get it to work with my opertations/functions
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace Phpwcfconsole
{
class program
{
static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost(typeof(Service1)))
{
try
{
host.Open();
Console.WriteLine("Host open. Press any key to <EXIT>");
Console.ReadLine();
host.Close();
}
catch (Exception e)
{
Console.WriteLine(Environment.NewLine + e.Message);
host.Close();
}
}
}
}
}
app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<compilation debug="true" />
</system.web>
<system.serviceModel>
<services>
<service behaviorConfiguration="Phpwcfconsole.Service1Behavior"
name="Phpwcfconsole.Service1">
<endpoint
address=""
binding="basicHttpBinding"
contract="Phpwcfconsole.IService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://agent007:8732/phpwcf/" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="Phpwcfconsole.Service1Behavior">
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
<bindings>
<basicHttpBinding>
<binding name="MyServiceBinding"
hostNameComparisonMode="StrongWildcard"
receiveTimeout="00:10:00"
sendTimeout="00:10:00"
openTimeout="00:10:00"
closeTimeout="00:10:00"
maxReceivedMessageSize="20000000"
maxBufferSize="20000000"
maxBufferPoolSize="20000000"
transferMode="Buffered"
messageEncoding="Text"
textEncoding="utf-8"
bypassProxyOnLocal="false"
useDefaultWebProxy="true" >
<security mode="None" />
</binding>
</basicHttpBinding>
</bindings>
</system.serviceModel>
</configuration>
IService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace Phpwcfconsole
{
[ServiceContract]
public interface IService
{
[OperationContract]
string GetData(int value);
}
}
Serverfunctions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Phpwcfconsole
{
public partial class Service1 : IService
{
public string GetData(int value)
{
throw new Exception("error");
}
}
}
ExeceptionHandler.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Description;
using System.Collections.ObjectModel;
using System.ServiceModel.Configuration;
namespace Phpwcfconsole
{
public class GlobalExceptionHandler : IErrorHandler
{
public bool HandleError(Exception ex)
{
return true;
}
public void ProvideFault(Exception ex, MessageVersion version,
ref Message msg)
{
// Do some logging here
var newEx = new FaultException(
string.Format("CALLED FROM YOUR GLOBAL EXCEPTION HANDLER BY {0}",
ex.TargetSite.Name));
MessageFault msgFault = newEx.CreateMessageFault();
msg = Message.CreateMessage(version, msgFault, newEx.Action);
}
}
public class GlobalExceptionHandlerBehaviourAttribute : Attribute, IServiceBehavior
{
private readonly Type _errorHandlerType;
public GlobalExceptionHandlerBehaviourAttribute(Type errorHandlerType)
{
_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)
{
var handler = (IErrorHandler)Activator.CreateInstance(_errorHandlerType);
foreach (ChannelDispatcherBase dispatcherBase in serviceHostBase.ChannelDispatchers)
{
var channelDispatcher = dispatcherBase as ChannelDispatcher;
if (channelDispatcher != null)
channelDispatcher.ErrorHandlers.Add(handler);
}
}
}
}
ok so if i put some console.writeLine inside
public class GlobalExceptionHandlerBehaviourAttribute : Attribute, IServiceBehavior
functions i see that they run when i start the program. but i cant get the example on the guide working with my function to throw a exception and get that one caught by my IErrorhandler.
i've tried some exceptions inside other functions and nothing happens with my IErrorhandler.
But one exception get caught in it that i discovered so far its when i add my service in Wcftestclient and then stop debug and remove [OperationContract] in my IService.cs and then start again and try to run the function without refreshing, that exception get caught by the IErrorhandler
so my problem here is why cant i catch exceptions inside a function?
thank you so much for answers.
c(:
Would the FaultContractAttribute be sufficient for what you are trying to do?
Take a look at the example in the msdn doc.
http://msdn.microsoft.com/en-us/library/system.servicemodel.faultcontractattribute.aspx
It sounds similar to what you are trying to do, with less complexity than a custom service behavior.
FaultContracts are the equivalent of exceptions when using WCF across processes/machines since consumers aren't necessarily .net clients.