简体   繁体   中英

Generic serializable WebAPI MVC4

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.

class MyAwesomeController : ApiController {
    public HttpResponseMessage ByYear(int year) {
        MyAwesomeViewModel[] models = Rep.GetByYear(year);
        return new HttpResponseMessage(statusGoesHere) { Content = GetUIContent(models) };
    }
}

class UIContent : HttpContent {
   ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM