so i am trying to do a general return for all WebAPI calls to our MVC4 framework project.
The problem i am running into is that the type object cannot be serialized easily.
So our return structure is this…,
[DataContract]
class UiOutput {
[DataMember("success")]
public bool Success {get;set;};
[DataMember("success")]
public object Data {get;set;};
}
This way every time a call is made it returns if it was successful or not and the data. The data could be an array of Models or whatever. Obviously, this is an easy task in php, but we are not there 🙂
So i read that the problem i am having is this, Error Three from site http://www.johnsoer.com/blog/?tag=the-type-was-not-expected-use-the-xmlinclude-or-soapinclude-attribute-to-specify-types-that-are-not-known-statically.
So i wanted to make a generic super class that could fix this except for how would it handle an array of ViewModels?
[XmlInclude(typeof(MyAwesomeViewModel))]
class SuperType { }
EXAMPLE:
[DataContract]
class UiOutput {
[DataMember("success")]
public bool Success {get;set;};
[DataMember("success")]
public SuperType Data {get;set;};
}
This will help return say
[DataContract]
class MyAwesomeViewModel {
[DataMember("awesome")]
public bool Awesome {get;set;};
[DataMember("viewModel")]
public string ViewModel {get;set;};
}
But if i have a controller that wants to return an array of MyAwesomeViewModel, then i do not know what to do!
What i mean is if there is a controller like
class MyAwesomeController : ApiController {
public UiOutput ByYear(int year) {
MyAwesomeViewModel[] models = Rep.GetByYear(year);
UiOutput output = new UiOutput();
output.success = true;
output.data = //Todo: Is there a way to overcome?
}
}
If you want a generic return value then use HttpResponseMessage and create a payload object that derives from HTTPContent.