响应Xml/Json请求ala Rails
问题描述:
例如,从Rails Guides。响应Xml/Json请求ala Rails
def index
@posts = Post.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @posts }
end
end
如果我调用这个控制器并且请求类型是html,那么给出一个视图。如果请求类型是xml,则给您XML。这里没有新东西。
在ASP.NET MVC中这样做的最好方法是什么?我知道你可以深入了解这个请求,但我很好奇别人在做什么。我是而不是问如何检查请求以查看请求类型是什么,我知道如何做到这一点,我正在寻找任何标准或很酷的方式来处理这个问题。可能有一些非常好的处理方法,我正在寻找一些想法。
事实上,我很惊讶,框架还没有从Rails复制这。
答
也许这样?
public class MyController : Controller
{
public ActionResult Index()
{
var posts = db.GetTable<Post>();
ViewData["Posts"] = posts;
return RespondTo(new ActionResultChoiceMap
{
{ "html",() => View() },
{ "json",() => Json(posts) },
});
}
}
与
class ActionResultChoiceMap : IEnumerable<ActionResultChoice>
{
public void Add(string key, Func<ActionResult> handler);
public ActionResult Get(string key);
}
和
ActionResult RespondTo(ActionResultChoiceMap map)
{
var key = ... // get desired result type from request
return map.Get(key);
}