现在的位置: 首页 > 综合 > 正文

《Pro ASP.NET MVC Framework》翻译——第一章

2012年03月09日 ⁄ 综合 ⁄ 共 15072字 ⁄ 字号 评论关闭

    自从ASP.NET MVC发布以来,一直备受关注,博客园中已有不少这方面的好文章,但对初学者来说,系统学习MVC的资料还是有些匮乏,一些国外的书籍相当优秀,但还未来得及出中文版,直接阅读英文版相对大多数人,花费的时间比较多,因此我这里尝试将这本书翻译出来,这大概是目前最新和最完整介绍ASP.NET MVC的书籍,希望能对初学者有所帮助。该书由Apress出版社出版,黑皮书,我想原版书的质量不用我说都能明白,翻译中我会尽我所能,但由于本人才疏学浅,无论英文水平,编程能力,还是文学修养方面都有待于提高,因此翻译之后的质量比起原版一定是大打折扣,也希望大家能多多指出错误和不足。翻译采取中英文对照,英文部分在上,翻译在下,以方便阅读者对照。

 

PART 1 Introducing ASP.NET MVC

ASP .NET MVC is a radical shift for web developers using the Microsoft platform. This new framework emphasizes clean architecture, design patterns, and testability. The first part of this book is designed to help you understand broadly the foundational ideas of ASP.NET MVC and to experience in practice what it’s like to use

第一部分ASP.NET MVC介绍

对于使用微软平台的web开发者而言,ASP.NET MVC是一个根本的转变。这个新的框架强调干净的架构,设计模式和可测试性。本书的第一部分帮助你理解ASP.NET MVC的基础并在实战中展示它用起来是什么样的。

 

CHAPTER 1  What’s the Big Idea?

ASP.NET MVC is a web development framework from Microsoft that combines the effectiveness and tidiness of model-view-controller (MVC) architecture, the most up-to-date ideas and techniques from agile development, and the best parts of the existing ASP.NET platform. It’s a complete alternative to “traditional” ASP.NET WebForms, delivering considerable advantages for all but the most trivial of web development projects.

 

第一章   到底是什么?

ASP.NET MVC是来自于微软的web开发平台,它是模型-视图-控制器(MVC)体系结构下效率与整洁的统一,该体系结构来源于敏捷开发最前沿的想法和技巧,也是现在ASP.NET平台最好的部分。它是“传统”ASP.NET WebForms模型的完全改变,对于所有项目都提供很大优势,尤其对于web开发项目是至关重要的。

 

A Brief History of Web Development

To understand the distinctive aspects and design goals of ASP.NET MVC, it’s worth considering the history of web development so far—brief though it may be. Among Microsoft’s web development platforms, we’ve seen over the years an ongoing increase in power and (unfortunately) complexity. As shown in Table 1-1, each new platform tackled the specific shortcomings of its predecessor.

 

Web开发的简要历史

要理解ASP.NET MVC的区别和设计目的,需要考虑迄今为止web开发的历史——虽然可能很简短。我们可以看到,在过去的数年中,微软的web开发平台在功能和复杂性(这点很不幸)上不断提高。如表1-1所示,每一个平台解决了它前辈的一个特定缺点。

 

Table 1-1.Microsoft’s Lineage of Web Development Technologies

Time Period

Technology

Strengths

Weakness

Jurassic

Common Gateway

Interface (CGI)*

Simple

Flexible

Only option at the time

Runs outside web server, so is resource

intensive (spawns separate OS process per

request)

Low-level

Bronze age

Microsoft Internet

Database Connector

(IDC)

Runs inside web server

Just a wrapper for SQL queries and templates

for formatting result set

1996

Active Server Pages (ASP)

General-purpose

Interpreted at runtime

Encourages “spaghetti code”

2002/03

ASP.NET 1.0/1.1

Compiled

Stateful” UI

Vast infrastructure

Encourages  object-oriented programming

Heavy on bandwidth

Ugly HTML

Untestable

2005

ASP.NET 2.0

2007

ASP.NET AJAX

2008

ASP.NET 3.5

* CGI is a standard means of  connecting a web server to an arbitrary executable program that returns dynamic content. Specification maintained by National Center for Supercomputing Applications (NCSA).

 

1-1.微软web开发技术世系

Time Period

Technology

Strengths

Weakness

侏罗纪

公共网关接口(CGI)*

简单

可扩展

当时唯一的选择

运行在web服务器外部,因此是资源密集的(

每个请求产生一个独立的操作系统进程)

低级

铜器时代

因特网数据库连接器

(IDC)

web 服务器内部运行

只是对sql查询和模版的包装,用于格式化结果集

 

1996

活动服务器页面(ASP)

通用

运行时解释

鼓励“意大利面条式代码”

2002/03

ASP.NET 1.0/1.1

编译的

具有“状态”的用户接口

庞大的架构

鼓励面向对象编程

带宽占用严重

丑陋的HTML标记

难以测试

2005

ASP.NET 2.0

2007

ASP.NET AJAX

2008

ASP.NET 3.5

*CGI是任意一个进程访问web服务器并返回动态内容的标准方法。该规范由美国国家超级计算应用中心(NCSA)维护。

 

In just the same way, ASP.NET MVC is designed to tackle the specific shortcomings of traditional ASP .NET WebForms, but this time by trying to emphasize simplicity.

 

同样,ASP.NET MVC被设计用来解决传统ASP.NET WebForms模型的特定缺点,但是这次重点强调简洁。

 

Traditional ASP.NET

ASP.NET was a huge shift when it first arrived, not just in terms of the brand-new .NET multilanguage managed code platform(which was a landmark in its own right), but in that it sought to close the gap between stateful, object-oriented Windows Forms development and stateless, HTML-oriented web development.

Microsoft attempted to hide both HTTP (with its intrinsic statelessness) and HTML(which, at the time, was unfamiliar to many developers) by modeling a user interface (UI) as a server-side hierarchy of control objects. Each control kept track of its own state across requests(using the ViewState facility), automatically rendered itself as HTML when needed, and automatically connected client-side events (e.g., a button click) with the corresponding server-side event handler code. In effect, WebForms is a giant abstraction layer aimed to deliver a classic event-driven GUI over the Web.

Developers no longer had to work with a series of independent HTTP requests and responses, as we did with earlier technologies; we could now think in terms of a stateful UI. We could “forget” about the Web, build UIs using a drag-and-drop designer, and imagine that everything happened on the server.

 

传统的ASP.NET

ASP.NET刚出现的时候是一个巨大的转变,不仅仅因为它是全新的.NET多语言托管代码平台(该平台本身也是一个里程碑),而是它试图填补具有状态的,面向对象的windows窗体开发和无状态的,面向HTMLweb开发之间的空白。

微软试图通过将用户接口(UI)建模为服务器端具有层次的控件来隐藏HTTP(其固有的无状态性)和HTML(在当时很多开发者并不熟悉)。每个控件在请求期间跟踪自己的状态(通过ViewState),在需要的时候自动呈现为HTML,并且自动连接客户端事件(例如一次按钮的点击)和相应的服务器端事件处理代码。事实上,WebForms是一种巨大的抽象,其目的是将传统的事件驱动的GUI用于web上。

开发者不必再象早期那样为了一系列独立的HTTP请求和响应而编写代码,我们现在只需要按照有状态的UI来考虑。我们可以“忘记”关于web的东西,通过拖拽建立UI,想象所有的事情都发生在服务器上。

 

What’s Wrong with Traditional ASP.NET?

Traditional ASP.NET was a fine idea, and a thrilling prospect at first, but of course reality turned out to be more complicated. Over the years, real-world use of WebForms uncovered a range of weaknesses:

ViewState: The actual mechanism of maintaining state across requests (ViewState) often results in giant blocks of data being transferred between client and server. It can reach hundreds of kilobytes in many real-world applications, and it goes back and forth with every request, frustrating site visitors with a long wait each time they click a button or try to move to the next page on a grid. ASP.NET Ajax suffers this just as badlyIt has to send the entire page’s ViewState data back and forth in each asynchronous request., even though bandwidth-heavy page updating is one of the main problems that Ajax is supposed to solve.

Page life cycle: The mechanism of connecting client-side events with server-side event handler code, part of the page life cycle, can be extraordinarily complicated and delicate. Few developers have success manipulating the control hierarchy at runtime without getting ViewState errors or finding that some event handlers mysteriously fail to execute.

Limited control over HTML: Server controls render themselves as HTML, but not necessarily the HTML you want. Not only does their HTML often fail to comply with web standards or make good use of CSS, but the system of server controls generates unpredictable and complex ID values, which are hard to access using JavaScript.

False sense of separation of concerns: ASP.NET’s code-behind model provides a means to take application code out of its HTML markup and into a separate code-behind class. This has been widely applauded for separating logic and presentation, but in reality, developers are encouraged to mix presentation code (e.g., manipulating the server-side control tree) with their application logic (e.g., manipulating database data) in these same monstrous code-behind classes.Without better separation of concerns, the end result is often fragile and unintelligible.

Untestable:When ASP.NET’s designers first set out their platform, they could not have anticipated that automated testing would become such a mainstream part of software development as it is today. Not surprisingly, the architecture they designed is totally unsuitable for automated testing.

ASP .NET has kept moving. Version 2.0 added a set of standard application components that can significantly reduce the amount of code you need to write yourself. The Ajax release in 2007 was Microsoft’s response to the Web 2.0/Ajax frenzy of the day, supporting rich client-side interactivity while keeping developers’ lives simple(Ironically, Microsoft actually invented XMLHttpRequest, the backbone of Ajax technology, to support Outlook Web Access. However, Microsoft didn’t really capitalize on its potential until hundreds of others already had.). The most recent 3.5 release is a smaller enhancement, adding support for .NET 3.5 features and a set of new controls. The new ASP .NET Dynamic Data facility generates simple database list/edit screens automatically. The forthcoming ASP.NET 4.0, to be shipped with Visual Studio 2010, will give developers the option of explicitly controlling certain HTML element IDs, reducing the problem of unpredictable and complex ID values.

 

ASP.NET有什么问题吗?

起初,ASP.NET是个好主意,并且令人兴奋,但事实上它太复杂了。 在过去的数年中,真实的WebForms程序显出一系列的缺点:

视图状态: 在请求之间维持状态的机制(视图状态)经常导致客户端与服务器之间大量数据的传送。 在真实的程序中,它能够达到数百K字节, 在每次请求之间来回传送, 每次站点的访问者需要点击一个按钮或者表格的下一页,都要经历令人沮丧的长时间等待。 ASP.NET Ajax在这一点上同样糟糕(它需要在每次异步请求中来回传递整个页面的状态., 虽然Ajax的一个主要目的是解决占用大量带宽页面的问题。

页面生命周期:页面生命周期中连接客户端与服务器事件的代码可能相当的复杂和精巧。很少有开发者能够在运行时成功的操纵控件的层次结构而没有视图状态的错误或者发现一些事件处理函数神秘失效。

HTML的有限控制:服务器控件将它们自身呈现为HTML,但可能不是想你想要的。它们产生的HTML不兼容web标准,没有有效利用CSS,并且生成不可预知的,复杂的ID,难以使用JavaScript来访问。

对分离关注的错误理解: ASP.NET的代码隐藏(code-behind)模型提供了一种将应用程序代码 从它的HTML标记中分离到一个单独的代码隐藏类里边。显示和逻辑的分离赢得了广泛的喝彩,但事实上,程序员被鼓励将显示的代码(例如操纵服务器端控件树)和应用程序逻辑(例如操作数据库)混合在同一个畸形的代码隐藏类里边。没有更好的分离关注,使得应用程序脆弱和难以理解。

难以测试:ASP.NET的设计者最初建立这个平台的时候,并没有预测到如今自动化测试会成为软件开发主流的一部分。因此,他们设计的体系结构总体上不适合自动化测试也就一点也不奇怪了。

ASP.NET在不停的前进。2.0增加了一系列标准的应用程序组件,大大减少了需要自己手动编写的代码。2007年发布的Ajax是微软对当时Web 2.0/Ajax的呼唤做出的响应,它在支持富客户端交互的同时,使得程序员象以前那样轻松编写代码(具有讽刺意味的是,虽然微软发明了XMLHttpRequest——这是Ajax技术的主要成分——来支持OutlookWeb的访问,但是直到Ajax被大量应用,微软才认识到它的潜力)。最近发布的3.5版本有一些小的改进,支持.NET 3.5的特性,增加了一系列新的控件。新的ASP.NET动态数据工具自动产生简单的数据库显示与编辑界面。即将到来的ASP.NET 4.0和随之而来的VS 2010,将给开发者提供显式控制HTML元素ID的机会,以减少无法预知的,复杂的ID带来的问题。

 

Web Development Today

Outside Microsoft, web development technology has been progressing rapidly in several different directions since WebForms was first released. Aside from Ajax, which I’ve already noted, there have been a few other major developments.

Web Standards and REST

The drive for web standards compliance hasn’t reduced in recent years; if anything, it’s increased. Web sites are consumed on a greater variety of devices and browsers than ever before, and web standards (for HTML, CSS, JavaScript, etc.) remain our one great hope for getting a decent browsing experience everywhere (even on the Internet-enabled refrigerator). Modern web platforms cannot afford to ignore the business case and the weight of developer enthusiasm for web standards compliance.

At the same time, REST is gaining enormous popularity as an architecture for application interoperability over HTTP—especially in the Web 2.0 world of informal “mash-ups.” The distinction between web services and web applications is eroding now that we have rich Ajax  and Silverlight clients, and REST dominates over SOAP in these scenarios. REST requires an approach to HTTP and URL handling that has not easily been supported by traditional ASP.NET.

Ruby on Rails

In 2004, Ruby on Rails was a quiet, open source contribution from an unknown player. Suddenly it hit fame, transforming the rules of web development. It’s not so much that it contained revolutionary technology, but more that it took existing ingredients and blended them in such a wonderful, magical, delicious way as to put existing platforms to shame.

By applying MVC architecture (an old pattern that many web frameworks have recently rediscovered), by working in tune with the HTTP protocol instead of against it, by promoting conventions instead of the need for configuration, and by integrating an object-relational mapping (ORM) tool into its core, Rails applications more or less fell into place without much expense or effort. It was as if this was how web development should have been all along; as if we’d suddenly realized we’d been fighting our tools all these years, but now the war was over.

Rails shows that web standards compliance and RESTfulness don’t have to be hard. It also shows that agile and test-driven development work best when the framework is designed to support them. The rest of the web development world has been catching up ever since.

 

今天的Web开发

在微软之外,自从WebForms第一次发布一来,web开发技术在几个不同的方向快速发展。除了已经提到的Ajax,还有一些其它的web开发技术。

Web 标准和 REST

对于web标准的兼容要求在过去的几年并没有减少,如果要说有什么的话,那就是这种兼容性要求在增加。和过去相比,Web站点现在被非常多的设备和浏览器访问,Web标准(象HTML, CSS ,JavaScript等等)依然是处处(即使是一个联网的冰箱)获得体面的浏览体验的一个很大的希望。现代的web平台不能忽略商业情形和开发者对于web标准兼容性的要求。

与此同时,REST作为一个通过HTTP进行应用程序互操作的架构收到热烈的欢迎,尤其是在Web 2.0时代非正式的“混搭”。现在我们拥有AjaxSilverlight富客户端,使得web服务和web程序的差别正在消失,在这些场景下,RESTSOAP更具优势。REST需要一个HTTPURL处理的入口,这是传统的ASP.NET很难支持的。

Ruby on Rails

2004, Ruby on Rails 是一个不知名的参与者贡献的默默无闻的开源网络应用架构。 它突然出名,改变了web开发的规则。它并没有包含多少革命性的技术,而是更多的采用现有的技术,以一种有趣,魔幻,宜人的方式混合在一起,使得现有的平台相形见绌。

通过应用MVC架构(这是一个被很多web框架最近重新发现的古老模式),通过使用HTTP协议的特点而不是反对它,通过使用约定而不是配置,通过整合对象-关系映射在其核心之中,Rails应用程序或多或少在它合适的位置上,并没有多少花费和努力。好像是web开发一直以来就应该是那样子,好像我们突然意识到这么多年来,我们一直在和我们的工具做斗争,而现在战争结束了。

Rails表明web标准的兼容和REST并不困难,它也表明框架支持敏捷和测试驱动的开发能工作得最好,其它的web开发技术从那时起都跟随上来了。

 

Key Benefits of ASP.NET MVC

A huge corporation like Microsoft can afford to rest on its laurels for a while, but not forever. ASP .NET has been a great commercial success so far, but as discussed, the rest of the web development world has moved on, and even though Microsoft has kept dusting the cobwebs off WebForms, its essential design has started to look quite antiquated.

In October 2007, at the very first ALT.NET conference in Austin, Texas, Microsoft vice president Scott Guthrie announced and demonstrated a brand-new MVC web development platform, built on ASP.NET, clearly designed as a direct response to the criticisms laid out previously. Here’s how it overcomes ASP.NET’s limitations and brings Microsoft’s platform back to the cutting edge.

 

ASP.NET MVC的关键好处

一个象微软这么大的公司,可以因为它的殊荣而停止一段时间,但不能永远。迄今为止,ASP.NET获得了商业上的巨大成功,但是,正如讨论过的,其它的web开发技术已经在前进,即使是微软在不断的清除WebForms的杂乱无章,它的基本的设计已经看起来相当陈旧了。

200710月,在德克萨斯州的奥斯汀的第一次ALT.NET会议上,微软的副总裁Scott Guthrie 宣布并且展示了全新的基于ASP.NETMVC web开发平台,它很明显的被设计为用来回应前边提到的种种批评。下边是它如何克服ASP.NET的限制并且把微软的平台带回到前沿。

 

Model-View-Controller Architecture

ASP .NET MVC provides greatly improved separation of concerns thanks to its adoption of MVC architecture. The MVC pattern isn’t new—it dates back to 1978 and the Smalltalk project at Xerox PARC—but it’s gaining enormous popularity today as an architecture for web applications, perhaps because of the following:

User interaction with an MVC application naturally follows a cycle: the user takes an action, and then in response the application changes its data model and delivers an updated view to the user. And then the cycle repeats. This is a very convenient fit for web applications delivered as a series of HTTP requests and responses.

Web applications already necessitate combining several technologies (e.g., databases, HTML, and executable code), usually split into a set of tiers or layers, and the patterns that arise naturally map onto the concepts in MVC.

ASP .NET MVC implements a modern variant on MVC that’s especially suitable for web applications. You’ll learn more about the theory and practice of this architecture in Chapter 3.

Through this design, ASP.NET MVC directly answers the competition of Ruby on Rails and similar platforms, making a serious effort to bring this style of development into the mainstream of the .NET world, capitalizing on the experience and best practices discovered by developers using other platforms, and in many ways pushing forward beyond what even Rails can offer.

 

模型-视图-控制器架构

由于采用了MVC架构,ASP.NET MVC在关注分离上有了很大的提高。MVC模式并不新颖,它可以追溯到1978年,Xerox PARC Smalltalk项目上,但是它在今天作为web应用程序的架构获得巨大的流行,可能是因为下边的原因:

  MVC应用程序的用户交互自然的遵从一个周期:用户有一个动作,然后作为响应,应用程序改变它的数据模型并且传送一个视图给用户,然后重复该周期。这非常适合传送一系列HTTP请求和响应的web应用程序。

Web应用程序需要组合几种技术(例如数据库,HTML和可执行代码),通常会被分为一系列的层级,在MVC中这些模式是很自然的概念。

ASP.NET MVCMVC的一个现代变体,尤其适合web应用程序。第三章将对该架构的理论和实践做更多的介绍。

通观整个设计,ASP.NET MVC直接回答了和Ruby on Rails及其它平台的竞争问题,努力将这种类型的开发理念融入到.NET世界的主流之中,利用其它开发者在别的平台上的经验和最佳实践,在很多方面甚至已经超越了Rails

 

Extensibility

Your desktop PC’s internal components are independent pieces that interact only across standard, publicly documented interfaces, so you can easily take out your graphics card or hard disk and replace it with another one from a different manufacturer, confident that it will slot in and work. In just the same way, the MVC Framework is built as a series of independent components—satisfying a .NET interface or built on an abstract base class—so you can easily replace the routing system, the view engine, the controller factory, or any other framework component, with a different one of your own implementation. In fact, the framework’s designers set out to give you three options for each MVC Framework component:

1. Use the default implementation of the component as it stands (which should be enough for most applications).

2. Derive a subclass of the default implementation to tweak its behavior.

3. Replace the component entirely with a new implementation of the interface or abstract base class.

It’ s like the Provider model from ASP.NET 2.0, but taken much further—right into the heart of the MVC Framework. You’ll learn all about the various components, and how and why you might want to tweak or replace each of them, starting with Chapter 7.

 

可扩展性

抱歉!评论已关闭.