Handling Invalid URI passed to a WCF service - wcf

I have WebGet, and WebInvoke attributes describing my contract, but what is the best method of handling invalid URI's? Right now, if a user passes an URI that does not match my current operations, they get an "Endpoint not found." message. I want to pass back a more descriptive message.
For example, my URI template looks like:
/Stuff/{ID}/subStuff
but say they type
/Stuff/{ID}/OtherStuff
There is no such thing as OtherStuff, and I do not have a template for that.
Is there a way to cover all non mapped URI's with a single contract?
Thanks!

If you want to catch all the unhandled requests at a global level in WCF REST then you have to create a custom WebHttpBehavior and custom IOperationInvoker as described in this post.
If you want to return a custom error text with custom status code(404) you can also look into the WebOperationContext.OutgoingResponse property as described here.

While I did follow the links mark provided, and they did give a hint of what I needed. The answers that were linked did not actually answer my original question.
I was able to follow the steps, and I wanted to list my steps to solve this problem on this question as well.
To create my own response to any URI that was not mapped to a method in my contract I created the following:
A custom ServiceHostFactory
Behavior that I mapped to my end points within the custom ServiceHostFactory
a dispatcher that would handle all unmapped uri's that were provided to the service.
Below are the full definitions of the object's I created:
using System.ServiceModel;
using System.ServiceModel.Activation;
namespace your.namespace.here
{
public class CustomServiceHostFactory : WebServiceHostFactory
{
protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
ServiceHost host = base.CreateServiceHost(serviceType, baseAddresses);
//note: these endpoints will not exist yet, if you are relying on the svc system to generate your endpoints for you
// calling host.AddDefaultEndpoints provides you the endpoints you need to add the behavior we need.
var endpoints = host.AddDefaultEndpoints();
foreach (var endpoint in endpoints)
{
endpoint.Behaviors.Add(new WcfUnkownUriBehavior());
}
return host;
}
}
}
As you can see above, we are adding a new behavior: WcfUnknownUriBehavior. This new custom behavior's soul duty is to replace the UnknownDispatcher. below is that implementation:
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Channels;
using System.ServiceModel.Web;
namespace your.namespace.here
{
public class UnknownUriDispatcher : IOperationInvoker
{
public object[] AllocateInputs()
{
//no inputs are really going to come in,
//but we want to provide an array anyways
return new object[1];
}
public object Invoke(object instance, object[] inputs, out object[] outputs)
{
var responeObject = new YourResponseObject()
{
Message = "Invalid Uri",
Code = "Error",
};
Message result = Message.CreateMessage(MessageVersion.None, null, responeObject);
WebOperationContext.Current.OutgoingResponse.ContentType = "text/html";
outputs = new object[1]{responeObject};
return result;
}
public System.IAsyncResult InvokeBegin(object instance, object[] inputs, System.AsyncCallback callback, object state)
{
throw new System.NotImplementedException();
}
public object InvokeEnd(object instance, out object[] outputs, System.IAsyncResult result)
{
throw new System.NotImplementedException();
}
public bool IsSynchronous
{
get { return true; }
}
}
}
Once you have these objects specified, you can now use the new factory within your svc's "markup":
<%# ServiceHost Language="C#" Debug="true" Service="your.service.namespace.here" CodeBehind="myservice.svc.cs"
Factory="your.namespace.here.CustomServiceHostFactory" %>
And that should be it. as long as your object "YourResponseObject" can be serialized, it's serialized representation will be sent back to the client.

Related

WCF - convert empty element to nullable native type

Leaving a SOAP field element empty results in a cast error for native types. (sadly cannot use xsi:nil="true" due to client constraints)
Marking the WCF contract native type as nullable<> does not appear to be enough to stop the following error being returned to the client.
The string '' is not a valid Boolean value.
at System.Xml.XmlConvert.ToBoolean(String s)
at System.Xml.XmlConverter.ToBoolean(String value)
System.FormatException
does anyone know the best method of instructing the DataContractSerializer to convert empty elements to be deserialized to null?
My example WCF service contract;
[ServiceContract()]
public interface IMyTest
{
[OperationContract]
string TestOperation(TestRequest request);
}
[ServiceBehavior()]
public class Settings : IMyTest
{
public string TestOperation(TestRequest request)
{
if (request.TestDetail.TestBool.HasValue)
return "Bool was specified";
else
return "Bool was null";
}
}
[DataContract()]
public class TestRequest
{
[DataMember(IsRequired = true)]
public int ID { get; set; }
[DataMember(IsRequired = true)]
public TestDetail TestDetail { get; set; }
}
[DataContract()]
public class TestDetail
{
[DataMember()]
public bool? TestBool { get; set; }
}
How can we get WCF to accept the following submission;
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ster="mynamespace">
<soapenv:Header/>
<soapenv:Body>
<ster:TestOperation>
<ster:request>
<ster:ID>1</ster:ID>
<ster:TestDetail>
<ster:TestBool></ster:TestBool>
</ster:TestDetail>
</ster:request>
</ster:TestOperation>
</soapenv:Body>
</soapenv:Envelope>
The client is only able to change the value it inserts <ster:TestBool>{here}</ster:TestBool> so true false or nothing are the only options.
Ok I believe I have cracked this by using an Operation Behavior to modify the underlying message before its formatted via IDispatchMessageFormatter.
The following code provides a solution against a service that is based on WCF file-less activation.
I wanted to have my IOperationBehavior live in the form of a Attribute class. Then I could simply decorate each Service Operation with my new attribute which would instigate the IOperationBehavior for that Operation - very nice and simple for the end user.
The key problem is where you apply the behavior, this is critical. The order of the operation behaviors that are called by WCF when applying the behavior via an attribute are different to when applying at the service host. The attribute based order is as follows:
System.ServiceModel.Dispatcher.OperationInvokerBehavior
MyOperationBehaviorAttribute
System.ServiceModel.OperationBehaviorAttribute
System.ServiceModel.Description.DataContractSerializerOperationBehavior
System.ServiceModel.Description.DataContractSerializerOperationGenerator
For some reason an operation behavior (only when applied via the use of an attribute) will be called before the DataContractSerializerOperationBehavior. This is a problem because in my behavior I want to delegate deserialization to the DataContractSerializerOperationBehavior Formatter (passed into my behavior as the inner formatter) within my formatter, after I have adjusted the message (see code). I don't want to have to re-write a deserialization routine when Microsoft provided a perfectly good deserializer already. I merely correct the XML in the first instance so that blanks are converted to nulls which are correctly represented within the XML so that the DataContractSerializer can tie them up to nullable types in the service interface.
So this means we cannot use attribute-based behaviors as they were intended since WCF may well be broken in a rather subtle way here since I can see no reason for this phenomenon. So we can still add an IOperationBehavior to an operation, we just have to manually assign it at the service host creation stage, because then our IOperationBehavior is inserted into the 'correct' sequence, that is, after the DataContractSerializerOperationBehavior has been created, only then can I get a reference to the inner formatter.
// This operation behaviour changes the formatter for a specific set of operations in a web service.
[System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple = false)]
public class NullifyEmptyElementsAttribute : Attribute
{
// just a marker, does nothing
}
public class NullifyEmptyElementsBahavior : IOperationBehavior
{
#region IOperationBehavior Members
public void AddBindingParameters(OperationDescription operationDescription, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation) { }
public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
{
// we are the server, we need to accept client message that omit the xsi:nill on empty elements
dispatchOperation.Formatter = new NullifyEmptyElementsFormatter(dispatchOperation.Formatter);
}
public void Validate(OperationDescription operationDescription) { }
#endregion IOperationBehavior Members
}
/// <summary>
/// This customized formatter intercepts the deserialization process to perform extra processing.
/// </summary>
public class NullifyEmptyElementsFormatter : IDispatchMessageFormatter
{
// Hold on to the original formatter so we can use it to return values for method calls we don't need.
private IDispatchMessageFormatter _innerFormatter;
public NullifyEmptyElementsFormatter(IDispatchMessageFormatter innerFormatter)
{
// Save the original formatter
_innerFormatter = innerFormatter;
}
/// <summary>
/// Check each node and add the xsi{namespace}:nil declaration if the inner text is blank
/// </summary>
public static void MakeNillable(XElement element)
{
XName _nillableAttributeName = "{http://www.w3.org/2001/XMLSchema-instance}nil"; // don't worry, the namespace is what matters, not the alias, it will work
if (!element.HasElements) // only end nodes
{
var hasNillableAttribute = element.Attribute(_nillableAttributeName) != null;
if (string.IsNullOrEmpty(element.Value))
{
if (!hasNillableAttribute)
element.Add(new XAttribute(_nillableAttributeName, true));
}
else
{
if (hasNillableAttribute)
element.Attribute(_nillableAttributeName).Remove();
}
}
}
public void DeserializeRequest(System.ServiceModel.Channels.Message message, object[] parameters)
{
var buffer = message.CreateBufferedCopy(int.MaxValue);
var messageSource = buffer.CreateMessage(); // don't affect the underlying stream
XDocument doc = null;
using (var messageReader = messageSource.GetReaderAtBodyContents())
{
doc = XDocument.Parse(messageReader.ReadOuterXml()); // few issues with encoding here (strange bytes at start of string), this technique resolves that
}
foreach (var element in doc.Descendants())
{
MakeNillable(element);
}
// create a new message with our corrected XML
var messageTarget = Message.CreateMessage(messageSource.Version, null, doc.CreateReader());
messageTarget.Headers.CopyHeadersFrom(messageSource.Headers);
// now delegate the work to the inner formatter against our modified message, its the parameters were after
_innerFormatter.DeserializeRequest(messageTarget, parameters);
}
public System.ServiceModel.Channels.Message SerializeReply(System.ServiceModel.Channels.MessageVersion messageVersion, object[] parameters, object result)
{
// Just delegate this to the inner formatter, we don't want to do anything with this.
return _innerFormatter.SerializeReply(messageVersion, parameters, result);
}
}
public class MyServiceHost : ServiceHost
{
public MyServiceHost(Type serviceType, params Uri[] baseAddresses)
: base(serviceType, baseAddresses) { }
protected override void OnOpening()
{
base.OnOpening();
foreach (var endpoint in this.Description.Endpoints)
{
foreach (var operation in endpoint.Contract.Operations)
{
if ((operation.BeginMethod != null && operation.BeginMethod.GetCustomAttributes(_NullifyEmptyElementsBahaviorAttributeType, false).Length > 0)
||
(operation.SyncMethod != null && operation.SyncMethod.GetCustomAttributes(_NullifyEmptyElementsBahaviorAttributeType, false).Length > 0)
||
(operation.EndMethod != null && operation.EndMethod.GetCustomAttributes(_NullifyEmptyElementsBahaviorAttributeType, false).Length > 0))
{
operation.Behaviors.Add(new NullifyEmptyElementsBahavior());
}
}
}
}
}
Perhaps since I am only modifying the incoming message, I could instead use IDispatchMessageInspector which will remove the dependency on the IDispatchMessageFormatter activation order. But this works for now ;)
Usage:
Add to your operation
[ServiceContract(Namespace = Namespaces.MyNamespace)]
public interface IMyServiceContrct
{
[OperationContract]
[NullifyEmptyElements]
void MyDoSomthingMethod(string someIneteger);
}
Tie into your service
A. if you have .svc simply reference MyServiceHost
<%# ServiceHost
Language="C#"
Debug="true"
Service="MyNameSpace.MyService"
Factory="MyNameSpace.MyServiceHost" %>
B. if your using file-less activation services, add this to your web.config file
<system.serviceModel>
... stuff
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" >
<!-- WCF File-less service activation - there is no need to use .svc files anymore, WAS in IIS7 creates a host dynamically - less config needed-->
<serviceActivations >
<!-- Full access to Internal services -->
<add relativeAddress="MyService.svc"
service="MyNameSpace.MyService"
factory="MyNameSpace.MyServiceHost" />
</serviceActivations>
</serviceHostingEnvironment>
... stuff
</system.serviceModel>

Implementing unit of work in a WCF service with Autofac

How can I implement unit of work pattern in a WCF service with Autofac?
Injecting the same instance per call (or in Autofac terms LifetimeScope) of the unit of work interface into my services and repositories is easy using Autofac's wcf integration - what I am after is a way to commit the unit of work changes on return of WCF service call obviously ONLY if there has not been any exceptions.
I have seen Using a Custom Endpoint Behavior with WCF and Autofac which is basically how I started out but that does not deal with exceptions.
Currently what I have is an IOperationInvoker that starts the unit of work in the Invoke and commits it only if there has not been any exceptions. The problem with this approach is that I need to resolve my unit of work instance inside the Invoke method which gives me a different instance than the one injected into my services and repositories using AutofacInstanceProvider.
Bradley Boveinis found a solution to this problem. We have not thoroughly tested it but it seems to work:
public class UnitOfWorkAwareOperationInvoker : IOperationInvoker
{
private readonly IOperationInvoker _baseInvoker;
public UnitOfWorkAwareOperationInvoker(IOperationInvoker baseInvoker)
{
_baseInvoker = baseInvoker;
}
public object[] AllocateInputs()
{
return _baseInvoker.AllocateInputs();
}
public object Invoke(object instance, object[] inputs, out object[] outputs)
{
var result = _baseInvoker.Invoke(instance, inputs, out outputs);
var context = OperationContext.Current.InstanceContext.Extensions.Find<AutofacInstanceContext>();
try
{
context.Resolve<IUnitOfWork>().Save();
}
catch (Exception ex)
{
var message = Message.CreateMessage(MessageVersion.Default, string.Empty);
new ElmahErrorHandler().ProvideFault(ex, null, ref message);
throw;
}
return result;
}
public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
{
return _baseInvoker.InvokeBegin(instance, inputs, callback, state);
}
public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
{
return _baseInvoker.InvokeEnd(instance, out outputs, result);
}
public bool IsSynchronous
{
get { return _baseInvoker.IsSynchronous; }
}
}
The key is in the following line:
OperationContext.Current.InstanceContext.Extensions.Find<AutofacInstanceContext>();
This grabs the UoW out of the ambient/current/contextual LifetimeScope.

AutoFac - Instantiating an unregistered service with known services

Instantiating an unregistered service with known services (injecting them via ctr).
I want to avoid container pollution.
Here is another way to resolve unregistered concrete types from container. Note that all autofac constructor finding and selecting logic, all registration event handlers remain in force.
First, you define this method:
public static object ResolveUnregistered(this IComponentContext context, Type serviceType, IEnumerable<Parameter> parameters)
{
var scope = context.Resolve<ILifetimeScope>();
using (var innerScope = scope.BeginLifetimeScope(b => b.RegisterType(serviceType)))
{
IComponentRegistration reg;
innerScope.ComponentRegistry.TryGetRegistration(new TypedService(serviceType), out reg);
return context.ResolveComponent(reg, parameters);
}
}
The idea is that you get component registration from derived context and resolve it in the current context.
Then you can create some handy overloads:
public static object ResolveUnregistered(this IComponentContext context, Type serviceType)
{
return ResolveUnregistered(context, serviceType, Enumerable.Empty<Parameter>());
}
public static object ResolveUnregistered(this IComponentContext context, Type serviceType, params Parameter[] parameters)
{
return ResolveUnregistered(context, serviceType, (IEnumerable<Parameter>)parameters);
}
public static TService ResolveUnregistered<TService>(this IComponentContext context)
{
return (TService)ResolveUnregistered(context, typeof(TService), Enumerable.Empty<Parameter>());
}
public static TService ResolveUnregistered<TService>(this IComponentContext context, params Parameter[] parameters)
{
return (TService)ResolveUnregistered(context, typeof(TService), (IEnumerable<Parameter>)parameters);
}
I found a solution that required some custom code. Somethings are specific to my app, but I think you can get the picture.
Resolve(parameter.ParameterType) would be a call to your container.
public object ResolveUnregistered(Type type)
{
var constructors = type.GetConstructors();
foreach (var constructor in constructors)
{
try
{
var parameters = constructor.GetParameters();
var parameterInstances = new List<object>();
foreach (var parameter in parameters)
{
var service = Resolve(parameter.ParameterType);
if (service == null) throw new NopException("Unkown dependency");
parameterInstances.Add(service);
}
return Activator.CreateInstance(type, parameterInstances.ToArray());
}
catch (NopException)
{
}
}
throw new NopException("No contructor was found that had all the dependencies satisfied.");
}
Here is a way to resolve an unregistered type with know constructor (ctor) properties. This is based on a previous great post: https://stackoverflow.com/a/6994144/2641447.
In this solution, it is absolutely great that constructor finding and selecting logic is handled by Autofac.
The comment is referred to dispose issues what I have solved with the 'ExternallyOwned()' wich configure the component so that instances are never disposed by the container.
I think that an improvement of the solution may be the following:
public static object ResolveUnregistered(this IComponentContext context, Type serviceType, IEnumerable<Parameter> parameters)
{
var scope = context.Resolve<ILifetimeScope>();
using (var innerScope = scope.BeginLifetimeScope(b => b.RegisterType(serviceType).ExternallyOwned()))
return innerScope.Resolve(serviceType, parameters);
}
The usings:
using Autofac;
using Autofac.Core;
using System;
using System.Collections.Generic;

WCF security via message headers

I'm trying to implement "some sort of" server-client & zero-config security for some WCF service.
The best (as well as easiest to me) solution that I found on www is the one described at http://www.dotnetjack.com/post/Automate-passing-valuable-information-in-WCF-headers.aspx (client-side) and http://www.dotnetjack.com/post/Processing-custom-WCF-header-values-at-server-side.aspx (corrisponding server-side).
Below is my implementation for RequestAuth (descibed in the first link above):
using System;
using System.Diagnostics;
using System.ServiceModel;
using System.ServiceModel.Configuration;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Description;
using System.ServiceModel.Channels;
namespace AuthLibrary
{
/// <summary>
/// Ref: http://www.dotnetjack.com/post/Automate-passing-valuable-information-in-WCF-headers.aspx
/// </summary>
public class RequestAuth : BehaviorExtensionElement, IClientMessageInspector, IEndpointBehavior
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string headerName = "AuthKey";
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string headerNamespace = "http://some.url";
public override Type BehaviorType
{
get { return typeof(RequestAuth); }
}
protected override object CreateBehavior()
{
return new RequestAuth();
}
#region IClientMessageInspector Members
// Keeping in mind that I am SENDING something to the server,
// I only need to implement the BeforeSendRequest method
public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
{
throw new NotImplementedException();
}
public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
{
MessageHeader<string> header = new MessageHeader<string>();
header.Actor = "Anyone";
header.Content = "TopSecretKey";
//Creating an untyped header to add to the WCF context
MessageHeader unTypedHeader = header.GetUntypedHeader(headerName, headerNamespace);
//Add the header to the current request
request.Headers.Add(unTypedHeader);
return null;
}
#endregion
#region IEndpointBehavior Members
public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{
throw new NotImplementedException();
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
clientRuntime.MessageInspectors.Add(this);
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
throw new NotImplementedException();
}
public void Validate(ServiceEndpoint endpoint)
{
throw new NotImplementedException();
}
#endregion
}
}
So first I put this code in my client WinForms application, but then I had problems signing it, because I had to sign also all third-party references eventhough http://msdn.microsoft.com/en-us/library/h4fa028b(v=VS.80).aspx at section "What Should Not Be Strong-Named" states:
In general, you should avoid strong-naming application EXE assemblies. A strongly named application or component cannot reference a weak-named component, so strong-naming an EXE prevents the EXE from referencing weak-named DLLs that are deployed with the application.
For this reason, the Visual Studio project system does not strong-name application EXEs. Instead, it strong-names the Application manifest, which internally points to the weak-named application EXE.
I expected VS to avoid this problem, but I had no luck there, it complained about all the unsigned references, so I created a separate "WCF Service Library" project inside my solution containing only code above and signed that one.
At this point entire solution compiled just okay.
And here's my problem:
When I fired up "WCF Service Configuration Editor" I was able to add new behavior element extension (say "AuthExtension"), but then when I tried to add that extension to my end point behavior it gives me:
Exception has been thrown by the target of an invocation.
So I'm stuck here.
Any ideas?
You have some:
throw new NotImplementedException();
in your code. These could be the exceptions that are being thrown. Try removing these and see if you get the same error.
Shiraz Bhaiji is right. The framework does call those methods that you are throwing not implemented exceptions. Remove that.

Logging requests/responses in a WCF REST service

I'm looking for a way to log both requests and responses in a WCF REST service. The WCF REST starter kit comes with a RequestInterceptor class which can be used to intercept requests, but there does not seem to be an equivalent for responses. Ideally, I'd like to be able to intercept a response just before it's sent over the wire, e.g. when the underlying service method returns. Any suggestions?
Notice that if you want to intercept the raw message, and not the parameters, you can inject your implementation of IDispatchMessageInspector instead of the IParameterInspector extension point that Dani suggests.
There is a technic in WCF:
you create InstrumentedOperationAttribute that derives from Attribute, IOperationBehavior.
Inside you implement:
public void ApplyDispatchBehavior(
OperationDescription operationDescription,
DispatchOperation dispatchOperation
)
{
dispatchOperation.ParameterInspectors.Add(
new ServerPI()
);
}
and the ServerPI() class is what does the magic:
you do everything you need in beforecall and aftercall methods:
class ServerPI : IParameterInspector
{
public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
{
Guid result = (Guid)correlationState;
// ...
}
public object BeforeCall(string operationName, object[] inputs)
{
string parameter1 = inputs[0] as string;
return Guid.NewGuid();
}
}