سؤال

I have a simple REST service in which ResponseFormat of all methods set to Json. When I use RestSharp client, I always receive the response in XML. But when I am using Fiddler to call the same methods, I am receiving response in Json as expected.

And one more interesting thing is that the calls made from RestSharp client are not logged in Fiddler. So I cannot check what is going on.

This is my service:

[ServiceContract]
public interface IService1
{          
    [WebInvoke(UriTemplate = "Create", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
    SampleItem Create(SampleItem instance);        

    [WebGet(UriTemplate = "Get/{id}", ResponseFormat = WebMessageFormat.Json)]
    SampleItem Get(string id);       
}

And this is SimpleItem class:

public class SampleItem
{
        public string Id { get; set; }
        public string StringValue { get; set; }
}

and this is how i am making call suing RestSharp client:

var request = new RestRequest("Create", Method.POST);
var newItem = new SampleItem { Id = "12347", StringValue = "Value 1" };
request.RequestFormat = DataFormat.Json;
request.AddBody(newItem);
var responce = client.Execute<SampleItem>(request);
var respObj = responce.Data;
Console.WriteLine("Id:{0}, StringValue:{1}", respObj.Id, respObj.StringValue);

I am using RestSharp version 104.4.

Is there something I need to set on the client to be able to receive response in Json?

هل كانت مفيدة؟

المحلول

Per https://groups.google.com/forum/#!topic/restsharp/KD2lsaTC0eM:

The Accept header is automatically generated by inspecting the "handlers" that are registered with the RestClient instance. One option is to use RestClient.ClearHandlers(); and then add back explicitly the JSON deserializer with RestClient.AddHandler("application/json", new JsonDeserializer ());

You can ensure that your RestSharp (and other .NET traffic) is captured by Fiddler by following these steps: http://fiddlerbook.com/fiddler/help/hookup.asp#Q-DOTNET

نصائح أخرى

In my case RestRequest.AddHeader("Accept", "application/json"); RestRequest.AddJsonBody(myobject); solved my issue.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top