【问题标题】:Generic serializable WebAPI MVC4通用可序列化 WebAPI MVC4
【发布时间】:2012-08-16 16:24:18
【问题描述】:

所以我正在尝试对我们的 MVC4 框架项目的所有 WebAPI 调用进行一般返回。

我遇到的问题是object 类型不能轻易序列化。

所以我们的返回结构是这样的......,

[DataContract]
class UiOutput {
    [DataMember("success")]
    public bool Success {get;set;};
    [DataMember("success")]
    public object Data {get;set;};
}

这样每次调用都会返回是否成功和数据。数据可以是模型数组或其他任何东西。显然,这在php 中是一件容易的事,但我们不在那里:)

所以我读到我遇到的问题是 Error Three 来自站点 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

所以我想创建一个通用的超类来解决这个问题,除了它如何处理 ViewModel 数组?

[XmlInclude(typeof(MyAwesomeViewModel))]
class SuperType { }

示例:

[DataContract]
class UiOutput {
    [DataMember("success")]
    public bool Success {get;set;};
    [DataMember("success")]
    public SuperType Data {get;set;};
}

这将有助于返回说

[DataContract]
class MyAwesomeViewModel {
    [DataMember("awesome")]
    public bool Awesome {get;set;};
    [DataMember("viewModel")]
    public string ViewModel {get;set;};
}

但如果我有一个控制器想要返回 MyAwesomeViewModel 的 array,那么我不知道该怎么办!

我的意思是如果有像这样的控制器

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?
    }
}

【问题讨论】:

  • 如果我有什么不清楚的地方,请告诉我,我会马上修改
  • HTTP 已经有一个成功的状态码,不需要在正文中复制。

标签: c# serialization asp.net-web-api


【解决方案1】:

如果您想要一个通用返回值,请使用 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 {
   ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-24
    • 1970-01-01
    • 2016-10-18
    • 1970-01-01
    • 1970-01-01
    • 2014-04-24
    相关资源
    最近更新 更多