[英]Best practice for returning XML data in ASP.net MVC2
我想知道從MVC2應用程序創建XML輸出並將其返回給客戶端的最佳方法是什么(可能還使用XSD方案驗證)?
我知道我不能直接從控制器返回它,也不能將其作為變量等傳遞給視圖。我的應用程序的很大一部分是在不同的XML源,模式和格式之間進行轉換,因此從一開始就正確設置它非常重要。
但是還有更好的方法嗎?
提前致謝!
您可以編寫一個自定義ActionResult ,它將視圖模型序列化為XML。 行中的東西:
public class XmlResult : ActionResult
{
private readonly object _model;
public XmlResult(object model)
{
_model = model;
}
public override void ExecuteResult(ControllerContext context)
{
if (_model != null)
{
var response = context.HttpContext.Response;
var serializer = new XmlSerializer(_model.GetType());
response.ContentType = "text/xml";
serializer.Serialize(response.OutputStream, _model);
}
}
}
接着:
public ActionResult Foo()
{
SomeViewModel model = ...
return new XmlResult(model);
}
隨時執行ExecuteResult
方法中可能需要的任何XSD驗證等。
正如@Robert Koritnik在評論部分中所建議的那樣,您還可以編寫擴展方法:
public static class ControllerExtensions
{
public static ActionResult Xml(this ControllerBase controller, object model)
{
return new XmlResult(model);
}
}
接着:
public ActionResult Foo()
{
SomeViewModel model = ...
return this.Xml(model);
}
這就是說,如果您發現自己需要交換大量XML,則可以考慮使用WCF。 如果需要POX,請考慮使用WCF REST。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.