AuthorizeAttribute、ActionFilterAttribute、HandleErrorAttribute

 

動作過濾器 (Action Filters) 的流程圖

圖片來源:https://blog.miniasp.com/post/2010/08/14/ASPNET-MVC-Developer-Note-Part-19-The-using-in-Action-method.aspx

 

一、ActionFilterAttribute

 

範例:一個自訂 ActionFilter 的基本用法

一個假想惡搞需求,我想要針對每一個頁面的最後都附上醜醜的簽名檔。

資料結構如圖

 

SignName.cs

using System.Web.Mvc;

namespace WebApplication1.Filter
{
    public class SignName : ActionFilterAttribute
    {
        public string name { get; set; }
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            string output = string.Format("---***{0} to visit, right here***---", name);
            filterContext.HttpContext.Response.Write(output);
        }
    }
}

 

HomeController.cs

using System.Web.Mvc;
using WebApplication1.Filter;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        [SignName(name = "Tom")]
        public ActionResult Index()
        {
            return View();
        }

        [SignName(name = "Mary")]
        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        [SignName(name = "Jim")]
        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

 

二、AuthorizeAttribute

 

範例:一個自訂 AuthorizeFilter 的基本用法

固定會驗證失敗的 AuthorizeFilter 目地只是展示結構用法。

資料結構如圖

 

Permission.cs

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

namespace WebApplication1.Filter
{
    public class Permission : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (!AuthorizeCore(filterContext.HttpContext))
            {
                HandleUnauthorizedRequest(filterContext);
            }
        }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            return httpContext.User.Identity.IsAuthenticated;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            filterContext.Result = new RedirectResult("https://www.google.com.tw/");
        }
    }
}

 

HomeController.cs

using System.Web.Mvc;
using WebApplication1.Filter;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [Permission]
        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

 

三、HandleErrorAttribute

暫不舉例。

 

參考資料:

AuthorizeAttribute Class