您的位置:首页 > 编程语言 > ASP

Asp.Net MVC 2.0 Filter基本用法

2013-10-09 16:22 399 查看
在这一节里,大家一同学习下mvc 2.0中的filter,简单的说,filter就是标记在action上的一些属性,来实现对action的控制。

mvc2.0中主要包括以下filter

1. Authorize

2.HandleError

3.RequireHttps

4.OutputCache

1. 首先说下Authorize

Authorize主要用来实现用户的授权与访问。

[csharp] view plaincopyprint?

[Authorize(Roles="Admins",Users="zx")]

public ActionResult DellUser(string userName)

{

return View("about");

}

[Authorize(Roles="Admins",Users="zx")]
public ActionResult DellUser(string userName)
{
return View("about");
}

上面的代码表明DellUser这个action只能被角色为admins下的zx用户访问,其他用户和角色均被禁止访问

2.HandleError

[csharp] view plaincopyprint?

[HandleError(Order=1,ExceptionType=typeof(ArgumentException),View="Error")]

[HandleError(Order=2,ExceptionType=typeof(Exception))]

public ActionResult DellUser(string userName)

{

if (string.IsNullOrEmpty(userName))

{

thrownew ArgumentException();

}

return View("about");

}

[HandleError(Order=1,ExceptionType=typeof(ArgumentException),View="Error")]
[HandleError(Order=2,ExceptionType=typeof(Exception))]
public ActionResult DellUser(string userName)
{
if (string.IsNullOrEmpty(userName))
{
throw new ArgumentException();
}
return View("about");
}

HandleError用作异常处理,其中order表示处理异常的顺序,数字越小,优先级越高。

ExceptionType表示异常类型

View表示出现异常后转向的页面.

3.OutputCache

[csharp] view plaincopyprint?

[OutputCache(Duration=60)]

public ActionResult DellUser(string userName)

{

return View("about");

}

[OutputCache(Duration=60)]
public ActionResult DellUser(string userName)
{
return View("about");
}

OutputCache用来表示页面缓存,在WEBFORM时代,在ASP.NET页面中可以直接设置这个属性,在MVC中直接在ACTION上标记属性。

4. RequireHttps

[csharp] view plaincopyprint?

[RequireHttps]

public ActionResult DellUser(string userName)

{

return View("about");

}

[RequireHttps]
public ActionResult DellUser(string userName)
{
return View("about");
}

RequireHttps表示DellUser这个action只能使用https协议才能访问,使用其他协议不行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: