user1391118
user1391118

Reputation: 265

set both the HTTP Accept and Content-Type headers to "application/xml" in C#

I created a web service (REST) in C#. Now I want that when someone uses it, it should return JSON or XML as per Header. I found a very good tutorial here. I followed it but I dont know where it says set both the HTTP Accept and Content-Type headers to "application/xml", I am calling it in this way http://localhost:38477/social/name. I can answer to any question if my question is not very clear to you Thanks THis is my code

[WebInvoke(UriTemplate = "{Name}", Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml)]
        public MyclassData Get(string Name)
        {
            // Code to implement
            return value;

        }

Upvotes: 7

Views: 73064

Answers (3)

Despertar
Despertar

Reputation: 22392

What framework are you using (Looks like the older WCf Web Api) to build your RESTful service? I would highly recommend using Microsofts new MVC4 Web API. It is really starting to mature and greatly simplifies building RESTful services. It is what is going to be supported in the future where the WCF Web API is about to be discontinued.

You simply return your ModelClass as a return type and it will automatically serialize it into XML or JSON depending on the requests accept header. You avoid having writing duplicate code and your service will support a wide range of clients.

public class TwitterController : ApiController
{
     DataScrapperApi api = new DataScrapperApi();
     TwitterAndKloutData data = api.GetTwitterAndKloutData(screenName);
     return data;
}

public class TwitterAndKloutData
{
   // implement properties here
}

Links

You can get MVC4 Web Api by downloading just MVC4 2012 RC or you can download the whole Visual Studio 2012 RC.

MVC 4: http://www.asp.net/mvc/mvc4

VS 2012: http://www.microsoft.com/visualstudio/11/en-us/downloads


For the original wcf web api give this a shot. Examine the accept header and generate your response according to its value.

var context = WebOperationContext.Current
string accept = context.IncomingRequest.Accept;
System.ServiceModel.Chanells.Message message = null;

if (accept == "application/json")
   message = context.CreateJsonResponse<TwitterAndCloutData>(data);
else if (accept == "text/xml")
   message = context.CreateXmlResponse<TwitterAndCloutData>(data);

return message;

You would set the accept header on whatever client is initiated the request. This will differ depending on what type of client you are using to send the request but any http client will have a way to add headers.

WebClient client = new WebClient();
client.Headers.Add("accept", "text/xml");
client.DownloadString("domain.com/service");

To access the response headers you would use

WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";

Additional resources: http://dotnet.dzone.com/articles/wcf-rest-xml-json-or-both

Upvotes: 6

muruge
muruge

Reputation: 4133

You have specified the RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml in your WebInvoke attribute which restricts the format of both Request and Response to Xml. Remove the RequestFormat and ResponseFormat properties and let the framework work on it based on Http headers. Content-type header specifies the request body type and Accept header specifies the response body type.

Edit:

This is how you would send your requests using fiddler.

enter image description here

You could use Microsoft.Http and Microsoft.Http.Extensions dlls that comes with the REST starter kit for writing client side code. Below is a sample.

        var client = new HttpClient("http://localhost:38477/social");
        client.DefaultHeaders.Accept.AddString("application/xml");
        client.DefaultHeaders.ContentType = "application/xml";
        HttpResponseMessage responseMessage = client.Get("twitter_name");
        var deserializedContent = responseMessage.Content.ReadAsDataContract<YourTypeHere>();

Upvotes: 4

Misha
Misha

Reputation: 571

Can you create two overloads for your method like this:

    [WebInvoke(UriTemplate = "dostuff", Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    public StuffResponse DoStuff(RequestStuff requestStuff)


    [WebInvoke(UriTemplate = "dostuff", Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml)]
    public StuffResponse DoStuff(RequestStuff requestStuff)

Upvotes: -1

Related Questions