[C#][ASP.NET MVC]自動更新網頁
自動更新網頁的功能可以使用client script來完成,但個人比較喜歡操作Action Filters,
這裡自己記錄一下。
新增自訂類別並繼承ActionFilterAttribute和覆寫OnResultExecuted
public class AutoRefreshAttribute :ActionFilterAttribute
{
public const Int32 DefaultDurationInSeconds =1200 ; //20 Minutes
public AutoRefreshAttribute()
{
DurationInSeconds = DefaultDurationInSeconds;
}
#region 公開相關屬性
public Int32 DurationInSeconds
{
get;
set;
}
public String RouteName
{
get;
set;
}
public String ControllerName
{
get;
set;
}
public String ActionName
{
get;
set;
}
#endregion
public override void OnResultExecuted( ResultExecutedContext filterContext )
{
String url = BuildUrl( filterContext );
String headerValue = String.Concat( DurationInSeconds, ";Url=", url );
//refresh web page
filterContext.HttpContext.Response.AppendHeader( "Refresh", headerValue );
base.OnResultExecuted( filterContext );
}
private string BuildUrl( ControllerContext filterContext )
{
String url = null;
UrlHelper urlHelper = new UrlHelper( filterContext.RequestContext );
if( !String.IsNullOrEmpty( RouteName ) )
url = urlHelper.RouteUrl( RouteName );
else if( !String.IsNullOrEmpty( ControllerName ) &&
!String.IsNullOrEmpty( ActionName ) )
url = urlHelper.Action( ActionName, ControllerName );
else if( !String.IsNullOrEmpty( ActionName ) )
url = urlHelper.Action( ActionName );
else
url = filterContext.HttpContext.Request.RawUrl;
return url;
}
}
Controller
[HandleError]
public class HomeController : Controller
{
/*[AutoRefreshAttribute(
ActionName = "LogOn", ControllerName = "Account", DurationInSeconds = 3600 )]*/
[AutoRefreshAttribute]//自訂Action Filters
public ActionResult Index()
{
ViewData[ "Message" ] = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult About()
{
return View();
}
}
附加Refresh Http Headers即可達到自動更新的功能,關於操作Action Filter其他功能可參考codeplex。
參考