tags:

views:

468

answers:

1

Hi,

I want to create a global option that when a REST call contains &format=json to output the response as a JSON string.

If I enter the following String in my method it works:

WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json;

However, if I add this line, anywhere in my Global.asax file, I get a nullException for Current Context:

String format = "";

if (HttpContext.Current.Request.QueryString["format"] != null)
  format = HttpContext.Current.Request.QueryString["format"];

if (String.Equals("json", format, StringComparison.OrdinalIgnoreCase))
  System.ServiceModel.Web.WebOperationContext.Current.OutgoingResponse.Format = System.ServiceModel.Web.WebMessageFormat.Json;

The exception is triggered here:

System.ServiceModel.Web.WebOperationContext.Current

Anyone know how I can add this functionality globally (WCF)?

+2  A: 

You can add your own DispatchMessageInspector to WCF processing pipeline via service behavior. Here is how to do that.

To apply behavior via config file at first you should derive new class from BehaviorExtensionElement and override members BehaviorType and CreateBehavior. Then add to config section similar to that (with your full type name)

<system.serviceModel>
    <extensions>
        <behaviorExtensions>
            <add name="myBehavior" type="SomeNamespace.MyBehaviorExtensionElement, AssemblyName,
                Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
       </behaviorExtensions>
    </extensions>
</system.serviceModel>

and that

<behaviors>
    <behavior configurationName="myServiceBehavior">
        <myBehavior />            
    </behavior>
</behaviors>

Finally apply this configuration to your service.

Denis Markelov
I created this, but it's just ignoring its existence. Any ideas?
Theofanis Pantelides
Maybe behavior wasn't properly attached to the service. You can show how you did that, and I think I will be able to help.
Denis Markelov
I think the problem is adding it to the web.configWhat do I need to add, so it stops ignoring me?
Theofanis Pantelides
Parser Error Message: Invalid element in configuration. The extension 'myBehavior' does not derive from correct extension base type 'System.ServiceModel.Configuration.BehaviorExtensionElement'.
Theofanis Pantelides
Check that your extension type is specified correctly. Is 'myBehavior' the name of your extension class?
Denis Markelov
namespace Wadja.API{ public class customExtensionsBehavior : IDispatchMessageInspector, IServiceBehavior {}}
Theofanis Pantelides
OK, I figured it out. It was ignoring me because I attached the behavior to a service, and I was testing outside of the Service1 spectrum
Theofanis Pantelides