![](/img/trans.png)
[英]MVC4 WebApi Routing with ActionNames not allowing for generic “Get”
[英]Generic serializable WebAPI MVC4
因此,我試圖為對我們的MVC4框架項目的所有WebAPI調用做一個一般性的歸還。
我遇到的問題是類型object
無法輕松序列化。
所以我們的回報結構就是這個……,
[DataContract]
class UiOutput {
[DataMember("success")]
public bool Success {get;set;};
[DataMember("success")]
public object Data {get;set;};
}
這樣,每次撥打電話都會返回是否成功以及數據。 數據可以是模型數組或其他任何東西。 顯然,這是php
的簡單任務,但是我們不存在:)
因此,我從網站http://www.johnsoer.com/blog/?tag=the-type-was-not-expected-use-the-xmlinclude-or-soapinclude讀取Error Three
,這是我遇到的問題歸因於靜態未知的指定類型 。
因此,我想制作一個可以解決此問題的通用超類,除了它將如何處理ViewModels數組之外?
[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?
}
}
如果要使用通用返回值,請使用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.