`

ASP.NET MVC与RAILS3的比较

阅读更多
进入后Web年代之后,MVC框架进入了快速演化的时代,Struts等垂垂老矣的老一代MVC框架因为开发效率低下而逐渐被抛弃,新一代的MVC则高举敏捷的大旗,逐渐占领市场,其中的代表有Rails (ruby), .NET MVC (.NET), Django (Python),Symfony (PHP)等等,这些框架的思想都大同小异,这里列举出Rails3和.NET MVC的一些的区别,以方便Web开发者从Rails迁移到.NET MVC,或者反之,从.NET MVC迁移到Rails.

生成项目
Rails和.NET MVC都能够产生项目的基本骨架,只是生成的方式略有不同,Rails采用的是命令行的方式:
rails tapir

而Microsoft则秉承其强大的IDE,提供了项目向导。

最终得到的目录结构,仅在测试和配置项上略有不同。
Rails ASP.NET MVC
/app/models /Models
/app/controllers /Controllers
/app/views/Views
/public/javascript/Scripts
/public/Content
/db/App_Data
/test单独的VS项目
/config /Global.asax, /Properties, Web.config


值得一提的是rails的一个亮点:rails可以预先配置三个不同的环境:开发、测试、最终产品,可以通过RAILS_ENV这个环境变量来做简单切换,.NET MVC并未提供这样的配置环境,你可以通过手工配置来完成。

模型Model
Rails默认采用ActiveRecord作为模型,当然切换到其他的框架也很简单,可选项有 Neo4J, MongoDB,和DataMapper。在Rails中,还是采用命令行来创建模型,Rails会生成一些骨架代码,包括:模型、迁移任务和测试。你可以用-o来选择其他模型、-t来选择其他测试框架:
$ rails g model customer name:string email:string
      invoke  active_record
      create    db/migrate/20100419094010_create_customers.rb
      create    app/models/customer.rb
      invoke    test_unit
      create      test/unit/customer_test.rb
      create      test/fixtures/customers.yml


Rails默认采用Sqlite3作为后台数据库,而且Rails会很贴心的为开发、测试、生产三个环境分别产生一个数据库拷贝。

在Rails中,所有的数据库的操作都通过脚本和迁移来完成,Rails中的迁移应该是最有价值的一个东西,当不同的开发者同时在修改一个数据库,或者您在升级现有的生产环境下的数据库,迁移就显示出它的强大威力:
class CreateCustomers < ActiveRecord::Migration

  # Called when migrating up to this version
  def self.up
    create_table :customers do |t|
      t.string :name
      t.string :email
      t.timestamps
    end
  end

  # Called when migrating down from this version
  def self.down
    drop_table :customers
  end
end


我们可以通过rake db:migrate命令迁移到不同的数据库版本上去。

和Rails不同的是,.NET MVC并为绑定一个模型框架,你要从既有的框架中选择一个适合你的,这个名单里可以用Nhibernate,Linq to SQL, Entity Framework,Castle ActiveRecord或者Ruby的ActiveRecord,不过.NET MVC没有迁移的概念,这有点遗憾。

大部分情况下Linq To SQL就很适合项目开发。

查询语言
Rails3使用AREL(Active Record Relations),LINQ-to-SQL则使用LINQ。 二者都是相当优美的语言
# A simple query with AREL
User.where(users[:name].eq('Anders')).order('users.id DESC').limit(20)


// The same with C#
// Lambda Syntax
db.Users.where(u => u.Name == "Anders").orderBy(u => u.Id).Take(20)

// LINQ Syntax
(from u in db.Users
where u.Name == "Anders"
orderby u.Id descending
select u).Take(20);


现在除了在.NET中采用Ruby的ActiveRecord(借助ironruby),目前还没有其他框架提供类似Ruby的findbyXXX的功能,不过C# 4.0的method_missing使得这类框架应该会很快出现(比如Nhibernate 3.0)

控制器
在.NET MVC中,你在Controller目录上点添加,就有很贴心的向导引导你为项目添加控制器,甚至还可以增加基本的CRUD的功能。
public class CustomersController : Controller {
      // GET: /Customers/
      public ActionResult Index() {
          return View();
      }

      // GET: /Customers/Details/5
      public ActionResult Details(int id) {
          return View();
      }

      // GET: /Customers/Create
      public ActionResult Create() {
          return View();
      }

      // POST: /Customers/Create
      [HttpPost]
      public ActionResult Create(FormCollection collection) {
          try {
              // TODO: Add insert logic here
              return RedirectToAction("Index");
          } catch {
              return View();
          }
      }
}


和Rails的脚手架代码一样,这些最基本的代码99%会被废弃,但是提供了“让程序跑起来看看”的基础。

Rails还是通过命令行来为项目增加控制器,你还可以在命令行里制定为控制器生成哪些Action。

过滤器
Rails很容易为某个Action添加个过滤器
class ItemsController < ApplicationController
  before_filter :require_user_admin, :only => [ :destroy, :update ]
  before_filter :require_user, :only => [ :new, :create]
end

.NET也不含糊,只要重载OnActionExecuting就可以实现同样的功能:
override void OnActionExecuting(ActionExecutingContext filterContext)
{
    var action = filterContext.ActionDescriptor.ActionName;
    if (new List<string>{"Delete", "Edit"}.Contains(action)) {
        RequireUserAdmin();
    }
    if ("Create".Equals(action)) {
        RequireUserAdmin();
    }
}

或者通过.NET的attribute更漂亮的完成
[RequireUserAdmin("Delete", "Edit")]
[RequireUser("Create")]
public class CustomersController : Controller


路由
在Rails中,可以修改routes.rb来修改路由,默认的Rails的路由被配置成RESTful:
Tapir::Application.routes.draw do |map|
  resources :animals

  get "customer/index"
  get "customer/create"

  match "/:year(/:month(/:day))" => "info#about",
	:constraints => { :year => /\d{4}/,
		:month => /\d{2}/,
		:day => /\d{2}/ }
  match "/secret" => "info#about",
	:constraints => { :user_agent => /Firefox/ }
end

通过rake routes你可以快速查看路由的结果。

ASP.NET MVC的路由稍微复杂一些,不过同样强大:
// Global.asax.cs
 public class MvcApplication : System.Web.HttpApplication {
	public static void RegisterRoutes(RouteCollection routes) {
		routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

		// Constrained route
		routes.MapRoute( "Product", "Product/{productId}",
			new {controller="Product", action="Details"},
			new {productId = @"\d+" } ); // Constraint

		// Route with custom constraint, defined below	
		routes.MapRoute( "Admin", "Admin/{action}",
			new {controller="Admin"},
			new {isLocal=new LocalhostConstraint()} );
	}
...
}

public class LocalhostConstraint : IRouteConstraint {
	public bool Match ( HttpContextBase httpContext, Route route,
	 	string parameterName, RouteValueDictionary values,
	 	RouteDirection routeDirection )
	{
		return httpContext.Request.IsLocal;
	}
} 


View
二者在View上的表现十分接近,添加控制器的时候,会自动创建相应的视图,规则也类似:视图所在的文件夹以控制器的名字命名,视图的文件名则以控制器的action命令,二者也都提供了从某个模型创建脚手架视图的能力。

Partials
Rails和Asp.NET MVC都提供了在文件中包含部分HTML文件能力,ASP.NET MVC的文件采用ASP,而Rails默认是ERB或HAML.
<!-- Rails -->
<%= render 'form' %>


<!-- ASP.NET MVC -->
<% Html.RenderPartial("Form", Model);%>


.NET MVC 2中更做出了一些改进,提倡用2个替代的方法来产生代码:
<%= DisplayFor("Address", m => m.Address ) %>

<%= EditorFor("Address", m => m.Address ) %>



尾声
这篇文章对Rails和.NET MVC作了一个快速的浏览,目的是让有相应编程经验的程序员能快速了解另一个框架。无论Rails还是.NET MVC,都只是一个工具,一个好的程序员应该能随心摆弄他的工具,而不是被工具所摆布。


参考:
http://blog.jayway.com/2010/04/23/asp-net-mvc-vs-rails3/
分享到:
评论
5 楼 typhoon555 2011-06-23  
学习了学习了学习了
4 楼 junxiang 2011-06-18  
这篇文章很有价值,我正在找asp.net mvc 跟 Rails比较的文章。
3 楼 yza0088 2010-08-01  
Asp.Net MVC 越来越像Rails了
2 楼 hongfei3 2010-07-30  
ray_linn 写道

无论Rails还是.NET MVC,都只是一个工具,一个好的程序员应该能随心摆弄他的工具,而不是被工具所摆布。


认同,最近想看看了。。。
1 楼 karl-barkmann 2010-07-28  
看过.Net MVC挺不错的,用起来也还算方便,只不过比起原来的三层模式开发,不太相同

只懂一点点ruby,rails3...没看过

相关推荐

    ASP.NET MVC实战

    贯穿《ASP.NET MVC实战》始终的是MVC框架的特性及其重要的设计理念(关注点分离、依赖注入等),一个完整的开发过程(包括建立模型、编码和测试)为开发人员提供了熟悉这一新框架的极好示范,同时揭示了与成熟的MVC框架...

    Test-Drive ASP.NET MVC

    Microsoft has addressed the shortcomings of ASP.NET and created a framework that goes toe-to-toe with other popular web frameworks such as Ruby on Rails. Programming in C# is fun again! This book ...

    ASP.NET MVC in Action

    除了ASP.NET MVC框架本身,作者还介绍了Onion Architecture、领域驱动设计(DDD)、测试驱动开发(TDD)、控制反转(IoC)以及其它一些真实项目中经常用到的类库(和技术)。 本书章节如下: ASP.NET MVC框架入门 ...

    《[精通ASP.NET.MVC.5框架》高清带书签

    第1章 ASP.NET MVC背景 1 1.1 理解ASP.NET历史 1 1.2 当今的Web开发 3 1.2.1 Web标准与REST 3 1.2.2 敏捷与测试驱动开发 3 1.2.3 Ruby on Rails 4 1.2.4 Node.js 4 1.3 ASP.NET MVC的关键优点 5 1.3.1 MVC的体系结构...

    ASP.NET MVC 2 in Action

    The ASP.NET MVC Framework was the vision of Scott Guthrie in early 2007. With a prototype demonstration in late 2007 and a key hire of Phil Haack as the Senior Program Manager of the feature team, Mr....

    ASP.Net MVC in Action

    Getting started with the ASP.NET MVC Framework 2. The model in depth 3. The controller in depth 4. The view in depth 5. Routing 6. Customizing and extending the ASP.NET MVC Framework 7. Scaling...

    Professional ASP.NET MVC 1.0原版第三部分

    This book begins with you working along as Scott Guthrie builds a complete ASP.NET MVC reference application. He begins NerdDinner by using the File-New Project menu command within Visual Studio to ...

    Professional ASP.NET MVC 1.0原版第五部分

    This book begins with you working along as Scott Guthrie builds a complete ASP.NET MVC reference application. He begins NerdDinner by using the File-New Project menu command within Visual Studio to ...

    Professional ASP.NET MVC 1.0原版第六部分

    This book begins with you working along as Scott Guthrie builds a complete ASP.NET MVC reference application. He begins NerdDinner by using the File-New Project menu command within Visual Studio to ...

    Professional ASP.NET MVC 1.0原版第四部分

    This book begins with you working along as Scott Guthrie builds a complete ASP.NET MVC reference application. He begins NerdDinner by using the File-New Project menu command within Visual Studio to ...

    Professional ASP.NET MVC 1.0 原版第二部分

    This book begins with you working along as Scott Guthrie builds a complete ASP.NET MVC reference application. He begins NerdDinner by using the File-New Project menu command within Visual Studio to ...

    asp.net mvc脚手架代码生成工具

    它是一个免费的工具,自动生成asp.net mvc的CRUD页面,主要特性如下:   Uses the LinqToSql data to generate source code.  Ruby on Rails like CRUD pages creator with a single button click.  Ruby on...

    FileUploadManager:ASP.NET MVC 5文件上传管理器

    ASP.NET MVC 5文件上传管理... 与支持标准HTML表单文件上传的任何服务器端平台( ASP.NET ,PHP,Python,Google App Engine,Ruby on Rails,Java等)一起使用。 对于此项目,我目前正在使用Visual Studio 2015,.NET

    mvc-respond-to:用于 ASP.NET MVC 的 Ruby On Rails respond_to 模拟

    Ruby on Rails的respond_to代码类似物对ASP.NET MVC NuGet 项目: 说明 该库为您的控制器提供了类似响应响应的 RoR 扩展方法。 简而言之, RespondTo允许您的操作根据客户端提交的 *HTTP Accept* 标头以不同的...

    debby.admin:Debby.Admin 是 ASP.NET MVC6 的管理仪表板,灵感来自 Rails Admin 和 Ilaro.Admin

    管理员 Debby.Admin 是 ASP.NET MVC6 的管理仪表板,灵感来自 Rails Admin 和 Ilaro.Admin。

    DBEntry.Net 参考手册

    It also provide DbEntryDataSource for ASP.NET 2.0 and a Rails style MVC framework and a simple IoC framework. The samples of the release package all TESTED on Sql Server 2005 Express, MySql 5.0, ...

    sc2_news:将starcraft.md从ASP.NET MVC移植到Ruby on Rails

    == SC2新闻 将starcrat.md移植到Ruby on Rails

    Angle - Bootstrap Admin Template(2016年6月最新版V3.4)part3

    ASP.NET MVC5/6 + AngularJS 完整应用模板和空模板; ASP.NET MVC5/6 + HTML5/jQuery 完整应用模板和空模板; Ruby on Rails HTML5/jQuery 完整应用模板和空模板; MeteorJS + AngularJS 完整应用模板和空模板; ...

Global site tag (gtag.js) - Google Analytics