问题 ASP.Net MVC中是否存在Ruby on Rails的respond_to format.xml等等?


在Ruby on Rails中,您可以编写一个简单的控制器操作,例如:

def index
    @movies = Movies.find(:all)

    respond_to do |format|
        format.html #index.html.erb
        format.xml  { render :xml => @movies }
        format.json { render :json => @movies }
    end
end

对于那些不熟悉RoR的人, def index 在这种情况下将相当于 public ActionResult Index() 在ASP.Net MVC控制器中,允许以下调用:

http://example.com/Movies/Index 从视图返回为html页面 index.html.erb (想想index.aspx)
http://example.com/Movies/Index.xml 以xml格式返回相同的数据(@movies 是包含所有视图使用的数据的对象)
http://example.com/Movies/Index.json 返回一个JSON字符串,在使javascript调用需要相同的数据/逻辑时非常有用

ASP.Net MVC中的等效流程(如果可能)可能看起来像这样(如果它可能更简洁,甚至更好):

public ActionResult Index()
{
    Movies movies = dataContext.GetMovies();
    // any other logic goes here

    switch (format)
    {
        case "xml":
            return View("XMLVIEW");
            break;
        case "json":
            return View("JSONVIEW");
            break;
        default:
            return View();
    }
}

这非常方便,不必让一堆不同的操作混乱你的控制器,有没有办法在ASP.Net MVC中做类似的事情?


6531
2018-01-08 18:52


起源

我不是一个Ruby家伙,但在哪里|格式|来自,一个请求标题? - DM.
添加了一些关于它如何运作的说明,希望它有所帮助。 - mynameiscoffey


答案:


在我的博客上,我详细介绍了一种处理它的方法,该方法的功能与它在Ruby on Rails中的功能非常相似。您可以在帖子底部找到链接,但这里是最终结果的示例:

public ActionResult Index()
{
    return RespondTo(format =>
    {
        format.Html = () => View();
        format.Json = () => Json(new { message = "hello world" });
    });
}

这是帖子的链接: http://icanhascode.com/2009/05/simple-ror-respond_to-functionality-in-aspnet-mvc/

它可以处理通过HTTP头以及路由中的变量检测正确的类型。


8
2018-02-15 03:24





所以我一直在玩这个并添加以下路由到RegisterRoutes():

routes.MapRoute("FormatAction", "{controller}/{action}.{format}",
                new { controller = "Home", action = "Index" });  

routes.MapRoute("FormatID", "{controller}/{action}/{id}.{format}",
                new { controller = "Home", action = "Index", id = "" });  

现在每当我需要一个控制器动作“格式感知”时,我只需添加一个 string format 对它的论证(如):

// Within Home Controller
public ActionResult MovieList(string format)
{
    List<Movie> movies = CreateMovieList();

    if ( format == "json" )
        return Json(movies);

    return View(movies);
}

现在我打电话的时候 /Home/MovieList 它会一如既往地返回标准的html视图,如果我打电话给 /Home/MovieList.json 它返回传递给视图的相同数据的JSON序列化字符串。这适用于您碰巧使用的任何视图模型,我只是为了修补而使用一个非常简单的列表。

为了使事情变得更好,您甚至可以在视图中执行以下操作:

链接到 /Home/MovieList
<%= Html.ActionLink("Test", "MovieList") %>

链接到 /Home/MovieList.json
<%= Html.ActionLink("JSON", "MovieList", new { format = "json" }) %>


6
2018-01-14 07:30





ASP.NET MVC中没有内置的支持。但是,您可以下载一个示例REST工具包:

阅读有关REST工具包的更多信息 菲尔的博客

REST工具包具有“格式提供程序”,用于定义各种请求的结果类型。可以在ASP.NET MVC 1.0的下载中获得该指导文档。以下是指导文件的摘录:

此控制器现在可以返回XML或JSON作为对HTTP GET请求的响应。格式是根据请求的内容类型或请求的Accepts标头中的内容类型确定的。


2
2018-01-09 22:18