I'm currently trying to build a little API, where I'm utilizing RestSharp. I have a method which should return a list of objects. However, I keep getting the following error when setting 'OnBeforeDeserialization' on my RestRequest:
'Init-only property or indexer 'RestResponseBase.ContentType' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or and 'init' accessor.
Here's my code:
public async Task<IEnumerable<MyObject>> GetMyObject()
{
var request = new RestRequest("/test", Method.Get);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var response = await _client.GetAsync<List<MyObject>>(request);
return response;
}
To my understanding, I am setting the init-property in an object initializer here: { resp.ContentType = "application/json"; }; What am I doing wrong?
CodePudding user response:
RestResponse.OnBeforeDeserialization is type of Action<RestResponse>, which essentially calls your callback with the a parameter of type RestResponse; it not initializing it. Since ContentType is an init-only setter, you can only set it when instantiating the object (you can try it for yourself by calling new RestResponse { ContentType = "application/json" };.
Moreover, I'm not sure why you are trying to explicitly set the content type for the response; this is something that the server you are talking to does. RestSharp supports both XML and JSON out of the box, for both requests and response deserialization. You can read more here.
