ASP.NET MVC與RAILS3的比較

來源:互聯網
上載者:User

標籤:des   blog   http   java   使用   strong   

進入後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採用的是命令列的方式: 

Java代碼  
  1. 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來選擇其他測試架構: 

Java代碼  
  1. $ rails g model customer name:string email:string  
  2.       invoke  active_record  
  3.       create    db/migrate/20100419094010_create_customers.rb  
  4.       create    app/models/customer.rb  
  5.       invoke    test_unit  
  6.       create      test/unit/customer_test.rb  
  7.       create      test/fixtures/customers.yml  



Rails預設採用Sqlite3作為後台資料庫,而且Rails會很貼心的為開發、測試、生產三個環境分別產生一個資料庫拷貝。 

在Rails中,所有的資料庫的操作都通過指令碼和遷移來完成,Rails中的遷移應該是最有價值的一個東西,當不同的開發人員同時在修改一個資料庫,或者您在升級現有的生產環境下的資料庫,遷移就顯示出它的強大威力: 

Java代碼  
  1. class CreateCustomers < ActiveRecord::Migration  
  2.   
  3.   # Called when migrating up to this version  
  4.   def self.up  
  5.     create_table :customers do |t|  
  6.       t.string :name  
  7.       t.string :email  
  8.       t.timestamps  
  9.     end  
  10.   end  
  11.   
  12.   # Called when migrating down from this version  
  13.   def self.down  
  14.     drop_table :customers  
  15.   end  
  16. 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。 二者都是相當優美的語言 

Java代碼  
  1. # A simple query with AREL  
  2. User.where(users[:name].eq(‘Anders‘)).order(‘users.id DESC‘).limit(20)  



Java代碼  
  1. // The same with C#  
  2. // Lambda Syntax  
  3. db.Users.where(u => u.Name == "Anders").orderBy(u => u.Id).Take(20)  
  4.   
  5. // LINQ Syntax  
  6. (from u in db.Users  
  7. where u.Name == "Anders"  
  8. orderby u.Id descending  
  9. select u).Take(20);  



現在除了在.NET中採用Ruby的ActiveRecord(藉助ironruby),目前還沒有其他架構提供類似Ruby的findbyXXX的功能,不過C# 4.0的method_missing使得這類架構應該會很快出現(比如Nhibernate 3.0) 

控制器 
在.NET MVC中,你在Controller目錄上點添加,就有很貼心的嚮導引導你為項目添加控制器,甚至還可以增加基本的CRUD的功能。 

Java代碼  
  1. public class CustomersController : Controller {  
  2.       // GET: /Customers/  
  3.       public ActionResult Index() {  
  4.           return View();  
  5.       }  
  6.   
  7.       // GET: /Customers/Details/5  
  8.       public ActionResult Details(int id) {  
  9.           return View();  
  10.       }  
  11.   
  12.       // GET: /Customers/Create  
  13.       public ActionResult Create() {  
  14.           return View();  
  15.       }  
  16.   
  17.       // POST: /Customers/Create  
  18.       [HttpPost]  
  19.       public ActionResult Create(FormCollection collection) {  
  20.           try {  
  21.               // TODO: Add insert logic here  
  22.               return RedirectToAction("Index");  
  23.           } catch {  
  24.               return View();  
  25.           }  
  26.       }  
  27. }  



和Rails的腳手架代碼一樣,這些最基本的代碼99%會被廢棄,但是提供了“讓程式跑起來看看”的基礎。 

Rails還是通過命令列來為項目增加控制器,你還可以在命令列裡制定為控制器產生哪些Action。 

過濾器 
Rails很容易為某個Action添加個過濾器 

Java代碼  
  1. class ItemsController < ApplicationController  
  2.   before_filter :require_user_admin, :only => [ :destroy, :update ]  
  3.   before_filter :require_user, :only => [ :new, :create]  
  4. end  


.NET也不含糊,只要重載OnActionExecuting就可以實現同樣的功能: 

Java代碼  
  1. override void OnActionExecuting(ActionExecutingContext filterContext)  
  2. {  
  3.     var action = filterContext.ActionDescriptor.ActionName;  
  4.     if (new List<string>{"Delete", "Edit"}.Contains(action)) {  
  5.         RequireUserAdmin();  
  6.     }  
  7.     if ("Create".Equals(action)) {  
  8.         RequireUserAdmin();  
  9.     }  
  10. }  


或者通過.NET的attribute更漂亮的完成 

Java代碼  
  1. [RequireUserAdmin("Delete", "Edit")]  
  2. [RequireUser("Create")]  
  3. public class CustomersController : Controller  



路由 
在Rails中,可以修改routes.rb來修改路由,預設的Rails的路由被配置成RESTful: 

Java代碼  
  1. Tapir::Application.routes.draw do |map|  
  2.   resources :animals  
  3.   
  4.   get "customer/index"  
  5.   get "customer/create"  
  6.   
  7.   match "/:year(/:month(/:day))" => "info#about",  
  8.     :constraints => { :year => /\d{4}/,  
  9.         :month => /\d{2}/,  
  10.         :day => /\d{2}/ }  
  11.   match "/secret" => "info#about",  
  12.     :constraints => { :user_agent => /Firefox/ }  
  13. end  


通過rake routes你可以快速查看路由的結果。 

ASP.NET MVC的路由稍微複雜一些,不過同樣強大: 

Java代碼  
  1. // Global.asax.cs  
  2.  public class MvcApplication : System.Web.HttpApplication {  
  3.     public static void RegisterRoutes(RouteCollection routes) {  
  4.         routes.IgnoreRoute("{resource}.axd/{*pathInfo}");   
  5.   
  6.         // Constrained route  
  7.         routes.MapRoute( "Product", "Product/{productId}",  
  8.             new {controller="Product", action="Details"},  
  9.             new {productId = @"\d+" } ); // Constraint  
  10.   
  11.         // Route with custom constraint, defined below    
  12.         routes.MapRoute( "Admin", "Admin/{action}",  
  13.             new {controller="Admin"},  
  14.             new {isLocal=new LocalhostConstraint()} );  
  15.     }  
  16. ...  
  17. }  
  18.   
  19. public class LocalhostConstraint : IRouteConstraint {  
  20.     public bool Match ( HttpContextBase httpContext, Route route,  
  21.         string parameterName, RouteValueDictionary values,  
  22.         RouteDirection routeDirection )  
  23.     {  
  24.         return httpContext.Request.IsLocal;  
  25.     }  
  26. }   



View 
二者在View上的表現十分接近,添加控制器的時候,會自動建立相應的視圖,規則也類似:視圖所在的檔案夾以控制器的名字命名,視圖的檔案名稱則以控制器的action命令,二者也都提供了從某個模型建立腳手架視圖的能力。 

Partials 
Rails和Asp.NET MVC都提供了在檔案中包含部分HTML檔案能力,ASP.NET MVC的檔案採用ASP,而Rails預設是ERB或HAML. 

Java代碼  
  1. <!-- Rails -->  
  2. <%= render ‘form‘ %>  



Java代碼  
  1. <!-- ASP.NET MVC -->  
  2. <% Html.RenderPartial("Form", Model);%>  



.NET MVC 2中更做出了一些改進,提倡用2個替代的方法來產生代碼: 

Java代碼  
  1. <%= DisplayFor("Address", m => m.Address ) %>  
  2.   
  3. <%= EditorFor("Address", m => m.Address ) %>  




尾聲 
這篇文章對Rails和.NET MVC作了一個快速的瀏覽,目的是讓有相應編程經驗的程式員能快速瞭解另一個架構。無論Rails還是.NET MVC,都只是一個工具,一個好的程式員應該能隨心擺弄他的工具,而不是被工具所擺布。 


參考: 
http://blog.jayway.com/2010/04/23/asp-net-mvc-vs-rails3/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.