resthttp-headerswcf-restrestsharp

RestSharp Usage


Recently I was using RestSharp to consume my Restful Resouce. and expected exchanging data with JSon between server and client. Below is my C# code.

var client = new RestSharp.RestClient();
var request = new RestRequest(sUrl,Method.POST);
request.RequestFormat = DataFormat.Json;
request.Timeout =  TIME_OUT_MILLISECONTS ;
request.AddHeader("Content-Type", "application/json");
request.AddBody(new { appID = sAppId, loginName = sUserName, password=sPassword });
var response = client.Execute(request);
string s=response.Content;//It is always XML format.

The result is not what I expected for(Json data format), although I had set the RequestFormat Json and add Http header Content-Type. So I decided to use the .Net Reflector to found out What happened in the RestClient.Execute method. Here is the code of the method.

public RestClient()
    {
        ...
        this.AddHandler("application/json", new JsonDeserializer());
        this.AddHandler("application/xml", new XmlDeserializer());
        this.AddHandler("text/json", new JsonDeserializer());
        this.AddHandler("text/x-json", new JsonDeserializer());
        this.AddHandler("text/javascript", new JsonDeserializer());
        this.AddHandler("text/xml", new XmlDeserializer());
        this.AddHandler("*", new XmlDeserializer());
        ...
    }

I have some questions about it:

  1. As the RestClient adds many kinds of Content-Type into the HttpWebRequest. Is it right way to build a Request? And I think Maybe that is the reason why Response.Content always XML.

  2. I don't know why the RestClient needs to build a HttpWebRequest like that. Any meaning to do that?

  3. If we specified both JSon and XMl message format in a Http Request, which one works finally? Is it allowed?

Thanks. Have a good day.


Solution

  • RestSharp will use the correct handler based on the content type of the response. That's what those AddHandlers are doing; its configuring the RestClient to accept certain content types in the response and mapping those types to deserializers. Normally you would want to set an accept header for the json content type which notifies the server to send json in the response.

    request.AddHeader("Accept", "application/json")
    

    Of course, this assumes that the server you are hitting is configured to respond with json.