ASPNET MVC3技术要点

更新时间:2023-06-09 19:51:01 阅读量: 实用文档 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

ASPNET MVC3技术要点

1

2

3

4

MVC3技术要点

MVC3模板结构....................................................................................................................... 3 1.1 目录与文件 ................................................................................................................... 3 1.2 约定 ............................................................................................................................... 3 1.3 Global.asax.cs的Application_Start()启动应用项目 ................................................... 4 路由配置 ................................................................................................................................... 5 2.1 基本配置 ....................................................................................................................... 5 2.2 带缺省值的基本配置 ................................................................................................... 5 2.3 变长配置 ....................................................................................................................... 6 2.4 特殊配置 ....................................................................................................................... 6 控制器....................................................................................................................................... 6 3.1 接收输入: ................................................................................................................... 7

3.1.1 从上下文对象(context)中提取数据 ........................................................... 7 3.1.2 通过动作函数参变量传递数据。 ................................................................... 7 3.1.3 显式调用框架的模型绑定功能 ....................................................................... 9 3.2 控制器输出 ................................................................................................................. 10

3.2.1 输出视图ViewResult ..................................................................................... 10 3.2.2 输出带数据的视图 ......................................................................................... 11 3.2.3 重新定向 ......................................................................................................... 14 3.2.4 输出Text数据 ................................................................................................ 15 3.2.5 输出文件或二进制数据 ................................................................................. 16 3.2.6 返回错误和HTTP代码 ................................................................................ 16 3.3 过滤应用 ..................................................................................................................... 16

3.3.1 身份验证过滤 ................................................................................................. 17 3.3.2 动作/结果过滤 ................................................................................................ 20 3.3.3 使用全局过滤 ................................................................................................. 21 3.3.4 使用OutputCache过滤器 .............................................................................. 21 视图......................................................................................................................................... 22 4.1 创建自定义视图引擎 ................................................................................................. 22

4.1.1 创建一个自定义的iView .............................................................................. 22 4.1.2 创建IVIEW引擎实现 ................................................................................... 23 4.1.3 注册自定义的视图引擎 ................................................................................. 23 4.1.4 测试自定义视图引擎 ..................................................................................... 23 4.2 添加动态内容到Razor视图 .................................................................................... 24 4.3 使用HTML助手 ........................................................................................................ 24

4.3.1 内置的HTML助手 ........................................................................................ 24 4.3.2 外部的自定义HTML助手 ............................................................................ 24 4.3.3 使用Form助手 ............................................................................................. 25 4.3.4 使用Input助手 .............................................................................................. 26 4.3.5 使用强类型输入助手 ..................................................................................... 26 4.3.6 使用Select助手 ............................................................................................ 27 4.3.7 使用URLs助手 ............................................................................................. 27 4.3.8 使用WebGrid助手 ....................................................................................... 28

ASPNET MVC3技术要点

5

4.3.9 使用Chart助手 ............................................................................................. 29 4.4 嵌入视图 ..................................................................................................................... 30

4.4.1 使用的部分视图 ............................................................................................. 30 4.4.2 使用子动作函数 ............................................................................................. 31 模型......................................................................................................................................... 32 5.1 使用客户端验证 ......................................................................................................... 32

5.1.1 启用和禁用客户端验证 ................................................................................. 32 5.1.2 实现客户端验证 ............................................................................................. 32 5.2 使用模板化视图助手 ................................................................................................. 33 5.3 使用模型元数据显示视图 ......................................................................................... 34 5.4 将属性数据与模型数据分离 ..................................................................................... 34 5.5 创建自定义的显示模板 ............................................................................................. 36 5.6 创建自定义编辑器模板 ............................................................................................. 36

ASPNET MVC3技术要点

1 MVC3模板结构

MVC3项目提供3种模板Empty、Internet Application和Intranet Application,它们产生结构如下图:

其中Internet Application模板内容最丰富。除Views目录外,其它目录下文件存放是惯例,可以任意存放。 1.1 目录与文件

1.1.1 App_Data目录用于存放数据文件,如XML的文件、SQL Server数据库文件 1.1.2 Content目录用于存放静态文件,如CSS文件、图片 1.1.3 Controllers目录用于存放控制器类文件

1.1.4 Models目录用于存放实体模型类、视图模型类文件 1.1.5 Scripts目录用于存放JavaScript、jQuery等库文件

1.1.6 Views目录用于存放视图,其子目录名与控制器名相对应 1.1.7 Views/Shared目录用于存放布局视图、与控制器无关的视图

1.1.8 /Global.asax是全局类文件,用于路由配置、应用初始化或结束需

要添加的代码

1.1.9 /Web.config应用配置文件

1.1.10 HomeController根视图控制器是惯例,可以是别的作为根视图控制器,这依

赖于路由配置

1.1.11 AccountController账号控制器,用于注册、登录视图控制 1.2 约定

ASPNET MVC3技术要点

1.2.1 控制器命名已Controller结尾,例如产品控制器为ProductController 1.2.2 控制器对应的视图必须存放在Views/控制器名目录下,例如ProductController

的视图必须存放在/Views/Product

1.2.3 动作函数使用return View();调用与动作函数同名的视图。如果使用不同名的

视图可以使用如return View("MyOtherView");方式指明视图名

1.2.4 对于布局的命名约定是前缀为_,放在/Views/Shared目录下。在

/Views/_ViewStart.cshtml中定义了所有视图的缺省布局文件,如果使用特定的布局文件,可在视图中使用如下语句: @{

Layout = "~/Views/Shared/MyLayout.cshtml"; }

如果视图不使用布局文件,可在视图中使用如下语句: @{

Layout = null; }

1.3 Global.asax.cs的Application_Start()启动应用项目

1.3.1 RegisterRoutes(RouteTable.Routes);语句调用RegisterRoutes(RouteCollection

routes)函数实现路由配置

1.3.2 还可以添加其它应用初始化语句。例如在SportsStore应用项目中

DependencyResolver.SetResolver(new NinjectDependencyResolver());语句实现项目范围内的依赖注入。NinjectDependencyResolver.cs代码如下:

using System;

using System.Collections.Generic; using System.Web.Mvc; using Ninject;

using Ninject.Parameters; using Ninject.Syntax;

using SportsStore.Domain.Abstract; using SportsStore.Domain.Concrete;

using SportsStore.WebUI.Infrastructure.Abstract; using SportsStore.WebUI.Infrastructure.Concrete; using System.Configuration;

namespace SportsStore.WebUI.Infrastructure {

public class NinjectDependencyResolver : IDependencyResolver { private IKernel kernel;

public NinjectDependencyResolver() { kernel = new StandardKernel(); AddBindings(); }

public object GetService(Type serviceType) { return kernel.TryGet(serviceType); }

public IEnumerable<object> GetServices(Type serviceType) { return kernel.GetAll(serviceType);

ASPNET MVC3技术要点

}

public IBindingToSyntax<T> Bind<T>() { return kernel.Bind<T>(); }

public IKernel Kernel { get { return kernel; } }

private void AddBindings() { // put additional bindings here

Bind<IProductRepository>().To<EFProductRepository>(); Bind<IAuthProvider>().To<FormsAuthProvider>(); // create the email settings object

EmailSettings emailSettings = new EmailSettings { WriteAsFile =

bool.Parse(ConfigurationManager.AppSettings["Email.WriteAsFile"] ?? "false") };

Bind<IOrderProcessor>() .To<EmailOrderProcessor>()

.WithConstructorArgument("settings", emailSettings); } } }

2

路由配置

可以在Global.asax.cs的RegisterRoutes(RouteCollection routes)函数中配置,可配置多个路由映射,如果该路由映射不匹配,就换下一个,如果都不匹配报异常 2.1 基本配置

2.1.1 不带参数的基本配置routes.MapRoute("MyRoute", "{controller}/{action}");它

适用给出控制器/动作函数的URL,例如http://localhost:2531/Admin/Index时调用AdminController控制器的Index动作函数。MyRoute是路由名 2.1.2 带参数的基本配置

routes.MapRoute(

"Default", // Route name

"{controller}/{action}/{id}", // URL with parameters); 如果URL中站点:端口/后的不是3段(用/分段)则匹配不成功

2.2 带缺省值的基本配置

routes.MapRoute(

"Default", // Route name

"{controller}/{action}/{id}", // URL with parameters

new { controller = "Product", action = "List", id = UrlParameter.Optional }

);

ASPNET MVC3技术要点

2.3

变长配置

routes.MapRoute(

"Default", // Route name

"{controller}/{action}/{id} /{*op}", // URL with parameters

new { controller = "Product", action = "List", id = UrlParameter.Optional }

2.4 特殊配置

将http://localhost/?page=2变为http://localhost/Page2只要添加

routes.MapRoute(

null, // we don't need to specify a name "Page{page}",

new { Controller = "Product", action = "List" } );

3

控制器

在MVC3中控制器只负责应用请求的处理,不涉及数据模型定义及数据的存储和操作管理;只提供应用显示所用的数据,不涉及数据的展示、不生成用户界面(视图)

ASPNET MVC3技术要点

3.1

接收输入:

3.1.1 从上下文对象(context)中提取数据

{

public ActionResult Info()

// Access various properties from context objects string url = Request.Url.ToString(); string serverName = Server.MachineName; string clientIP = erHostAddress; DateTime dateStamp = HttpContext.Timestamp; string userName = ;

ViewBag.Message = string.Format("URL = {0},serverName = {1},clientIP = {2},dateStamp = {3},userName = {4}",

url, serverName, clientIP, dateStamp, userName); return View(); }

3.1.2 通过动作函数参变量传递数据。

3.1.2.1 注意参变量必须实值,参变量可以取自Request.QueryString、

Request.Form,、RouteData.Values中的值,如果要使用引用变量必须为模型变量或模型变量集合。例如:

LogOn.cshtml视图代码如下:

@model SportsStore.WebUI.Models.LogOnViewModel @{

ViewBag.Title = "Admin: Log In";

Layout = "~/Views/Shared/_AdminLayout.cshtml"; }

<h1>Log In</h1>

ASPNET MVC3技术要点

<p>Please log in to access the administrative area:</p> @using(Html.BeginForm()) { @Html.ValidationSummary(true) @Html.EditorForModel()

<p><input type="submit" value="Log in" /></p> }

Account控制器LogOn动作函数代码:

[HttpPost]

public ActionResult LogOn(LogOnViewModel model, string returnUrl) {

if (ModelState.IsValid) {

if (authProvider.Authenticate(erName, model.Password)) {

return Redirect(returnUrl ?? Url.Action("Index", "Admin")); } else {

ModelState.AddModelError("", "Incorrect username or password"); return View(); } } else {

return View(); } } }

视图中引入视图模型变量LogOnViewModel,LogOn动作函数可以使用model参变量

为了防止参变量为空,可以设置缺省值。例如:

public ViewResult Search(string query= "all", int page = 1) {

// ... 其它语句 ...

}

3.1.2.2 动作函数参变量传入数据比手动从上下文对象中提取,使动作函数更

容易理解,也有利于单元测试。以下是两种方式的对比: public ActionResult ShowWeatherForecast(){ string city = RouteData.Values["city"];

DateTime forDate = DateTime.Parse(Request.Form["forDate"]); // ... 其它语句 ... }

可以改写为:

public ActionResult ShowWeatherForecast(string city, DateTime forDate){ // ... 其它语句 ...

ASPNET MVC3技术要点

}

3.1.3 显式调用框架的模型绑定功能

如果视图中无模型变量,需要将模型变量绑定到context。例如: ProductSummary.cshtml视图代码:

@model SportsStore.Domain.Entities.Product

<div class="item">

@if (Model.ImageData != null) {

<div style="float:left;margin-right:20px">

<img width="75" height="75" src="@Url.Action("GetImage", "Product", new { Model.ProductID })" /> </div> }

<h3>@</h3> @Model.Description

@using(Html.BeginForm("AddToCart", "Cart")) { @Html.HiddenFor(x => x.ProductID)

@Html.Hidden("returnUrl", Request.Url.PathAndQuery) <input type="submit" value="+ Add to cart" /> }

<h4>@Model.Price.ToString("c")</h4> </div>

Cart控制器AddToCart动作函数代码:

public RedirectToRouteResult AddToCart(Cart cart, int productId, string returnUrl) {

Product product = repository.Products.FirstOrDefault(p => p.ProductID == productId); if (product != null) {

//GetCart().AddItem(product, 1); cart.AddItem(product, 1); }

return RedirectToAction("Index", new { returnUrl }); }

ProductSummary.cshtml中没有Cart对象,那么AddToCart动作函数的参变量是从哪里来的呢?实际它是在CartModelBinder.cs中实现,代码如下:

public class CartModelBinder : IModelBinder {

private const string sessionKey = "Cart";

public object BindModel(ControllerContext controllerContext,

ModelBindingContext bindingContext)

{

// get the Cart from the session

Cart cart = (Cart)controllerContext.HttpContext.Session[sessionKey];

ASPNET MVC3技术要点

// create the Cart if there wasn't one in the session data if (cart == null) {

cart = new Cart();

controllerContext.HttpContext.Session[sessionKey] = cart; }

// return the cart return cart; } }

为完成绑定需要在Global.asax.cs的Application_Start()添加如下语句: ModelBinders.Binders.Add(typeof(Cart), new CartModelBinder()); 3.2 控制器输出

3.2.1 输出视图ViewResult

如果在/Views/<ControllerName>下找不视图名的文件会到/Views/Shared下寻找 3.2.1.1 返回与动作函数同名的视图 public ViewResult Index() {

return View(); }

3.2.1.2 返回指定名的视图 public ViewResult Index() {

return View("Homepage"); }

ASPNET MVC3技术要点

3.2.1.3 返回指定路径及名的视图 public ViewResult Index() {

return View("~/Views/Other/Index.cshtml"); }

3.2.2 输出带数据的视图

3.2.2.1 使用ViewBag 动作函数

public ViewResult Index() {

ViewBag.Message = "Hello"; ViewBag.Date = DateTime.Now; return View(); }

视图

@{

ViewBag.Title = "Index"; }

<h2>Index</h2>

The day is: @ViewBag.Date.DayOfWeek <p />

The message is: @ViewBag.Message <p />

3.2.2.2 使用变量 动作函数

public ViewResult Index() {

ViewData["Message"] = "Hello"; ViewData["Date"] = DateTime.Now;

ViewBag.Days = new[] { "Monday", "Tuesday", "Wednesday", "Etc" }; ViewBag.Fruits = new[] { "Apples", "Mango", "Bannana" };

List<Region> regionsData = new List<Region> {

new Region { RegionID = 7, RegionName = "Northern" }, new Region { RegionID = 3, RegionName = "Central" }, new Region { RegionID = 5, RegionName = "Southern" }, };

ViewData["region"] = new SelectList(regionsData, // items "RegionID", // dataValueField "RegionName", // dataTextField 0);

return View(); }

ASPNET MVC3技术要点

视图

@{

ViewBag.Title = "Index"; }

<h2>Index</h2> <p>

The day is: @(((DateTime)ViewData["Date"]).DayOfWeek) </p> <p>

The message is: @ViewData["Message"] </p> <p />

<h4>InlineHelper</h4> Days of the week: <p/>

@Html.CreateList((string[]) ViewBag.Days) <p />

Fruit I like: <p />

@Html.CreateList((string[]) ViewBag.Fruits) <p />

@Html.DropDownList("region", "Choose")

3.2.2.3 使用ViewModel ViewModel

public class ProductsListViewModel {

public IEnumerable<Product> Products { get; set; } public PagingInfo PagingInfo { get; set; } public string CurrentCategory { get; set; } }

动作函数

public ViewResult List(string category, int page = 1) {

ProductsListViewModel viewModel = new ProductsListViewModel {

Products = repository.Products

.Where(p => category == null || p.Category == category) .OrderBy(p => p.ProductID) .Skip((page - 1) * PageSize) .Take(PageSize),

PagingInfo = new PagingInfo {

CurrentPage = page, ItemsPerPage = PageSize, TotalItems = category == null ?

ASPNET MVC3技术要点

repository.Products.Count() : repository.Products.Where(e => e.Category == category).Count() },

CurrentCategory = category };

return View(viewModel); }

视图

@model SportsStore.WebUI.Models.ProductsListViewModel @{

ViewBag.Title = "Products"; }

@foreach (var p in Model.Products) {

Html.RenderPartial("ProductSummary", p); }

<div class="pager">

@Html.PageLinks(Model.PagingInfo, x => Url.Action("List", new {page = x, category = Model.CurrentCategory})) </div>

嵌入视图ProductSummary.cshtml

@model SportsStore.Domain.Entities.Product

<div class="item">

@if (Model.ImageData != null) {

<div style="float:left;margin-right:20px">

<img width="75" height="75" src="@Url.Action("GetImage", "Product", new { Model.ProductID })" /> </div> }

<h3>@</h3> @Model.Description

@using(Html.BeginForm("AddToCart", "Cart")) { @Html.HiddenFor(x => x.ProductID)

@Html.Hidden("returnUrl", Request.Url.PathAndQuery) <input type="submit" value="+ Add to cart" /> }

<h4>@Model.Price.ToString("c")</h4> </div>

为了实现动作函数的参变量传送,定义路由映射

routes.MapRoute(null,

"", // Only matches the empty URL (i.e. /)

new {

controller = "Product",

ASPNET MVC3技术要点

action = "List", category = (string)null, page = 1 } );

3.2.3 重新定向

重定向使用最频繁的是用在处理POST请求的动作函数。当用户要改变状态按提交按钮后,又按重新载入,那么采取处理POST请求后直接输出HTTP的动作函数会产生不可知后果的风险,安全做法是采用Post/Redirect/Get模式,因为处理POST请求后重定向,再收到的是一个GET请求而GET请求不会修改应用程序的状态,避免应用程序状态的不确定性。 3.2.3.1 重定向到一个确定网址 public RedirectResult Redirect() {

return Redirect("/Example/Index"); //发302码是临时定向 }

public RedirectResult Redirect() {

return RedirectPermanent("/Example/Index");//发301码是永久定向 }

实际应用的例子

[HttpPost]

public ActionResult LogOn(LogOnViewModel model, string returnUrl) {

if (ModelState.IsValid) {

if (authProvider.Authenticate(erName, model.Password)) {

return Redirect(returnUrl ?? Url.Action("Index", "Admin")); } else {

ModelState.AddModelError("", "Incorrect username or password"); return View(); } } else {

return View(); } }

3.2.3.2 重定向到一个动作函数

[HttpPost]

public ActionResult Delete(int productId) {

Product prod = repository.Products.FirstOrDefault(p => p.ProductID == productId);

ASPNET MVC3技术要点

if (prod != null) {

repository.DeleteProduct(prod);

TempData["message"] = string.Format("{0} was deleted", ); }

return RedirectToAction("Index"); }

3.2.3.3 重定向到一个路由系统的URL public RedirectToRouteResult Redirect() { return RedirectToRoute(new {

controller = "Example", action = "Index", ID = "MyID" }); }

3.2.4 输出Text数据

3.2.4.1 输出纯文字数据

public ContentResult Index() {

string message = "This is plain text";

return Content(message, "text/plain", Encoding.Default); }

3.2.4.2 输出XML数据

public ContentResult XMLData() {

StoryLink[] stories = {

new StoryLink("First example story" ,"This is the first example story","/Story/1"),

new StoryLink("Second example story" ,"This is the second example story","/Story/2"),

new StoryLink("Third example story" ,"This is the third example story","/Story/3")

};

XElement data = new XElement("StoryList", stories.Select(e => {

return new XElement("Story", new XAttribute("title", e.Title),

new XAttribute("description", e.Description), new XAttribute("link", e.Url)); }));

return Content(data.ToString(), "text/xml"); }

3.2.4.3 输出JSON数据

public JsonResult JsonData(string id) {

IEnumerable<Appointment> data = new[] {

ASPNET MVC3技术要点

new Appointment { ClientName = "Joe", Date = DateTime.Parse("1/1/2012")}, new Appointment { ClientName = "Joe", Date = DateTime.Parse("2/1/2012")}, new Appointment { ClientName = "Joe", Date = DateTime.Parse("3/1/2012")}, new Appointment { ClientName = "Jane", Date = DateTime.Parse("1/20/2012")}, new Appointment { ClientName = "Jane", Date = DateTime.Parse("1/22/2012")}, new Appointment {ClientName = "Bob", Date = DateTime.Parse("2/25/2012")}, new Appointment {ClientName = "Bob", Date = DateTime.Parse("2/25/2013")} };

if (!string.IsNullOrEmpty(id) && id != "All") {

data = data.Where(e => e.ClientName == id); }

var formattedData = data.Select(m => new {

ClientName = m.ClientName, Date = m.Date.ToShortDateString() });

return Json(formattedData, JsonRequestBehavior.AllowGet); }

3.2.5 输出文件或二进制数据

3.2.5.1 发送一个文件

public FileResult AnnualReport() {

string filename = @"h:\QS_Chinese.pdf"; string contentType = "application/pdf"; string downloadName = "QS_Chinese.pdf"; return File(filename, contentType, downloadName); }

3.2.5.2 发送一个字节数组

public FileContentResult DownloadReport() {

byte[] data = ... // Generate or fetch the file contents somehow return File(data, "application/pdf", "AnnualReport.pdf"); }

3.2.5.3 发送一个流的内容

public FileStreamResult DownloadReport(){

Stream stream = ...open some kind of stream... return File(stream, "text/html"); }

3.2.6 返回错误和HTTP代码

public HttpStatusCodeResult StatusCode() {

return new HttpStatusCodeResult(404, "URL cannot be serviced"); }

3.3 过滤应用

MVC框架支持四种不同类型的过滤器

ASPNET MVC3技术要点

MVC框架过滤使用的属性标志[属性名],该标志加在动作函数前对该函数起过滤作用,该标志加在控制器前对所有动作函数起过滤作用。 3.3.1 身份验证过滤

3.3.1.1 创建自定义的身份验证过滤器

using System; using System.Linq; using System.Web.Mvc; using System.Web;

namespace ControllersAndActions.Infrastructure.Filters {

public class CustomAuthAttribute : AuthorizeAttribute {

private string[] allowedUsers;

public CustomAuthAttribute(params string[] users) {

allowedUsers = users; }

protected override bool AuthorizeCore(HttpContextBase httpContext) {

return httpContext.Request.IsAuthenticated && allowedUsers.Contains(, StringComparer.InvariantCultureIgnoreCase); } } }

它是AuthorizeAttribute子类,所以必须实现AccountController.cs

using System.Web.Mvc; using System.Web.Security; using ControllersAndActions.Models;

namespace ControllersAndActions.Controllers {

public class AccountController : Controller {

public ActionResult LogOn() {

ASPNET MVC3技术要点

return View(); } [HttpPost]

public ActionResult LogOn(LogOnModel model, string returnUrl) {

if (ModelState.IsValid) {

FormsAuthentication.SetAuthCookie(erName, model.RememberMe); }

return RedirectToAction("Index", "Home"); }

public ActionResult LogOff() {

FormsAuthentication.SignOut();

return RedirectToAction("Index", "Home"); } } }

及LogOn.cshtml

@model ControllersAndActions.Models.LogOnModel @{

ViewBag.Title = "Admin: Log In"; }

<h1>Log In</h1>

<p>Please log in to access the administrative area:</p> @using(Html.BeginForm()) { @Html.ValidationSummary(true) @Html.EditorForModel()

<p><input type="submit" value="Log in" /></p> }

这里使用LogOnModel

using ponentModel.DataAnnotations; namespace ControllersAndActions.Models {

public class LogOnModel {

[Required]

[Display(Name = "User name")] public string UserName { get; set; }

[Required]

[DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; }

ASPNET MVC3技术要点

[Display(Name = "Remember me?")] public bool RememberMe { get; set; } } }

为了使用CustomAuthAttribute只要在控制器或动作函数前添加

[CustomAuth("adam", "steve", "bob")] public class HomeController : Controller

{ }

........

3.3.1.2 使用系统提供身份验证过滤器 使用Internet Application模板

3.3.1.2.1 数据库准备

3.3.1.2.1.1 从aspnetdb数据库导出生成选择特定数据库对象文件 3.3.1.2.1.2 修改文件中USE 语句为使用的数据库名,在文件末尾

添加以下语句

INSERT INTO [dbo].[aspnet_SchemaVersions] ([Feature]

,[CompatibleSchemaVersion] ,[IsCurrentVersion]) VALUES

('common','1',1) go

INSERT INTO [dbo].[aspnet_SchemaVersions] ([Feature]

,[CompatibleSchemaVersion] ,[IsCurrentVersion]) VALUES

('health monitoring','1', 1); go

INSERT INTO [dbo].[aspnet_SchemaVersions] ([Feature]

,[CompatibleSchemaVersion] ,[IsCurrentVersion]) VALUES

('membership', '1', 1) go

INSERT INTO [dbo].[aspnet_SchemaVersions] ([Feature]

,[CompatibleSchemaVersion] ,[IsCurrentVersion]) VALUES

ASPNET MVC3技术要点

('personalization','1', 1) go

INSERT INTO [dbo].[aspnet_SchemaVersions] ([Feature]

,[CompatibleSchemaVersion] ,[IsCurrentVersion]) VALUES

('profile','1', 1) go

INSERT INTO [dbo].[aspnet_SchemaVersions] ([Feature]

,[CompatibleSchemaVersion] ,[IsCurrentVersion]) VALUES

('role manager','1', 1) go

3.3.1.2.1.3 执行该文件所有语句

3.3.1.2.2 在需要是否认证的控制器或动作函数前添加

[Authorize]

public class HomeController : Controller

{ }

........

3.3.2 动作/结果过滤

3.3.2.1 编写属性操作文件 (例ProfileAllAttribute.cs)

using System.Diagnostics; using System.Web.Mvc;

namespace ControllersAndActions.Infrastructure.Filters {

public class ProfileAllAttribute : ActionFilterAttribute {

private Stopwatch timer;

public override void OnActionExecuting(ActionExecutingContext filterContext) {

timer = Stopwatch.StartNew(); }

public override void OnActionExecuted(ActionExecutedContext filterContext) {

timer.Stop();

filterContext.HttpContext.Response.Write( string.Format("Action method elapsed time: {0}",

ASPNET MVC3技术要点

timer.Elapsed.TotalSeconds)); }

public override void OnResultExecuting(ResultExecutingContext filterContext) {

timer = Stopwatch.StartNew(); }

public override void OnResultExecuted(ResultExecutedContext filterContext) {

timer.Stop();

filterContext.HttpContext.Response.Write( string.Format("Action result elapsed time: {0}", timer.Elapsed.TotalSeconds)); } } }

3.3.2.2 使用ProfileAll属性过滤

[ProfileAll]

public ViewResult Index() {

ViewBag.Message = "Hello"; ViewBag.Date = DateTime.Now; return View(); }

3.3.3 使用全局过滤

在Global.asax的 RegisterGlobalFilters函数中添加如下语句使ProfileAll成为一个全局过滤器

filters.Add(new ProfileAllAttribute());

3.3.4 使用OutputCache过滤器

当后续请求相同的URL, OutputCache过滤器告诉MVC框架的一个动作函数从缓存输出相同的内容可以重复使用,从而提高性能。下表是OutputCache过滤器可配置的参数:

本文来源:https://www.bwwdw.com/article/i3v1.html

Top