简体   繁体   English

通用可序列化的WebAPI MVC4

[英]Generic serializable WebAPI MVC4

so i am trying to do a general return for all WebAPI calls to our MVC4 framework project. 因此,我试图为对我们的MVC4框架项目的所有WebAPI调用做一个一般性的归还。

The problem i am running into is that the type object cannot be serialized easily. 我遇到的问题是类型object无法轻松序列化。

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 :) 显然,这是php的简单任务,但是我们不存在:)

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 . 因此,我从网站http://www.johnsoer.com/blog/?tag=the-type-was-not-expected-use-the-xmlinclude-or-soapinclude读取Error Three ,这是我遇到的问题归因于静态未知的指定类型

So i wanted to make a generic super class that could fix this except for how would it handle an array of ViewModels? 因此,我想制作一个可以解决此问题的通用超类,除了它将如何处理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! 但是,如果我有一个控制器想要返回MyAwesomeViewModel的array ,那么我不知道该怎么办!

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. 如果要使用通用返回值,请使用HttpResponseMessage并创建一个从HTTPContent派生的有效负载对象。

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

class UIContent : HttpContent {
   ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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