7.1Filter的使用
Filter的使用
-对Action的附加说明
Asp.net MVC中Filter
-Authorize
-HandleError
-OutputCache
-RequireHttps
AuthorizeAttribute标签
[Authorize(Roles=”Admins, SuperAdmins”)]
public class AdminController
{
//Only admins should see this.
public ActionResult Index()
{return View();}
//Only admins should see this.
public ActionResult DeleteAllUsers()
{//Thankfully, this is secured by the Authorize attribute.}}
----------------------------------------
[Authorize(Roles=”Admins, SuperAdmins”)]
public class AdminController{
//Only admins should see this.
public ActionResultIndex(){return View();}
//Only Phil should do this.
[Authorize(Users=”Phil”)]
public ActionResultDeleteAllUsers()
{
//…
}
}
Requirehttps
[RequireHttps] // Applies to this action only
public ActionResultIndex()
{
Return View();
}
[RequireHttps]
public class SampleController
{
// Will apply to all controller actions for this controller
}
OutputCache
?CacheProfile
?Duration
?Location
?NoStore //不保存缓存
?SqlDependency //
?VaryByContentEncoding //编码格式
?VaryByCustom //取决于调用
?VaryByHeader
?VaryByParam
[OutputCache(Duration=60, VaryByParam=”none”)]
public ActionResult About()
{
ViewData[“Title”] = “This was cached at “ + DateTime.Now;
return View();
}
<system.web>
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name=”MyProfile” duration=”60” varyByParam=”none” />
</outputCacheProfiles>
</outputCacheSettings>
</caching>
</system.web>
[OutputCache(CacheProfile=”MyProfile”)]
public ActionResultAbout()
{
ViewData[“Title”] = “This was cached at “ + DateTime.Now;
return View();
}
Exception Filter
[HandleError(ExceptionType= typeof(ArgumentException), View=”ArgError”)]
public ActionResultGetProduct(string name)
{
if(name == null)
{
throw new ArgumentNullException(“name”);
}
return View();
}
[HandleError(Order=1, ExceptionType=typeof(ArgumentException), View=”ArgError”)]
[HandleError(Order=2, ExceptionType=typeof(Exception)]
public ActionResult GetProduct(string name)
{…}
有顺序
2011-4-21 22:19 danny