WCF Rest Services: Setting the response format based on request's expected type

WCF Rest Services: Setting the response format based on request's expected type

In this article I will explain , Where WCF Rest response type (JSON or XML) is dynamically set based on the HTTP request's requested content type in the "Accepts" HTTP Header.

This purpose is achieved by switching between two different operation implementations (methods).

I liked the idea of using the requested content type to automatically return JSON or XML depending on the requested content type, but I wasn't so keen on having to implement two methods.

I thought I'd try to get a similar thing working but using a single operation implementation which is called no matter whether or JSON or XML are requested.

The DynamicResponseType attribute

This is how it works.  You decorate your method with an additional DynamicResponseType attribute which I have defined:

[ServiceContract]

[ServiceBehavior(IncludeExceptionDetailInFaults = true,

          InstanceContextMode = InstanceContextMode.Single,

         ConcurrencyMode = ConcurrencyMode.Single)

]

[AspNetCompatibilityRequirements(RequirementsMode =                    AspNetCompatibilityRequirementsMode.Allowed)]

public class Service1

{

       [OperationContract]

       [WebGet(UriTemplate = "GetData?param1={i}&param2={s}")]

       [DynamicResponseType]

      public SampleResponseBody GetData(int i, string s)

      {

              return new SampleResponseBody()

                {

                      Name = "Test",

                      Value = s,

                      Time = DateTime.Now.ToShortTimeString()

                 };

      }

}

public class SampleResponseBody

{

         public string Name { get; set; }

         public string Value { get; set; }

         public int IntValue { get; set; }

        public string Time { get; set; }

}

 

An example client

Then when the client requests a specific type (XML or JSON), it is served automatically.

Below I have a pure HTML/Javascript client with two buttons, each of which call the same  GetWebRequest function when they are clicked but passing a different requested content type as a parameter.  The GetWebRequest function issues an HTTP request to the WCF operation I showed above.

The first button says it wants JSON, and the second XML.  This is done by setting the "Accept" request header:



wRequest.get_headers()["Accept"] = acceptType;

</script>









from the same WCF Service operation

How it works.

I've created my own  WCF ServiceHostFactory which I wire up in the SVC file:




In my ServiceHostFactory2Ex class I ensure that my own WebServiceHost class gets created.

Then in my own WebServiceHost I ensure that my own WebHttpBehavior replaces the standard one.

Next in my own WebHttpBehavior I override the GetReplyDispatchFormatter method and return my own IDispatchMessageFormatter.

In my own IDispatchMessageFormatter I implement the SerializeReply method and then use a JSON formatter or XML formatter depending on the "Accepts" HTTP request header which I pick up from the OperationContext.Current.RequestContext.RequestMessage.

That's all Guyz :)
Thanx for Reading...

Really sory for Code ... Linked in Don't provide code snipet while publishing a post.

Ask if any question in comments :)

To view or add a comment, sign in

More articles by Rao Muhammad Qaiser Nadeem

  • Beginning with Elasticsearch in Python

    ElasticSearch (ES) is a disseminated and profoundly accessible open-source web engine that is based over Apache Lucene.…

  • Access MongoDB in Node app

    Learn how to access document-based database MongoDB using Node.js in this section.

  • Build Your Own REPL For Your Node App

    It turns out the REPL interface in NodeJS is a module that is built in to NodeJS core, and you can create your own…

  • WCF and ASP.NET Web API

    WCF is Microsoft’s unified programming model for building service-oriented applications. It enables developers to build…

Others also viewed

Explore content categories