Reputation: 10838
I have normal WebApi controller that with methods:
public class ModelController : ApiController
{
public IEnumerable<Model> Get()
{
return service.Get();
}
public string Get(int id)
{
return service.Get(id);
}
public void Post([FromBody]MyViewModel value)
{
return service.Save(value);
}
public void Put(int id, [FromBody]MyViewModel value)
{
return service.Save(value);
}
public void Delete(int id)
{
return service.Delete(value);
}
}
I want to wrap return results in to custom object ServiceResult
public class ServiceResult<T>
{
public bool IsError{ get; set; }
public T ObjectModel {get; set}
}
I want to change the return type on all my controller methods to ServiceResult Here is an example:
public ServiceResult Post([FromBody]MyViewModel value)
{
service.Save(value);
//getting error here:
return new ServiceResult() { IsError= true, ObjectModel = value };
}
But getting the error
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.
Type 'Models.View.MyViewModel' with data contract name 'MyViewModel://schemas.datacontract.org/2004/07/MyViewModel' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.
Do you have any idea how can I fix that?
Upvotes: 0
Views: 1615
Reputation: 282
Your ServiceResult object requires a type argument, Try this
return new ServiceResult<MyViewModel>() { IsError= true, ObjectModel = value };
Upvotes: 0