MVC 身份验证和异常处理过滤器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace FilterExam.Controllers
{
public class HomeController : Controller
{
//[MyAuthorization]//第一种方式
// GET: Home
public ActionResult Index()
{
return View();
}
public ActionResult Show()
{
return View();
}
//第二种方式
protected override void OnAuthorization(AuthorizationContext filterContext)
{
filterContext.HttpContext.Response.Write("456");
}
}
}
//身份验证过滤器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace FilterExam.Fiter
{
public class MyAuthorization:AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
// filterContext.Result = new RedirectResult(UrlHelper.GenerateUrl("", "Loin", "UserInfo", null, null, null, false));
filterContext.HttpContext.Response.Write("123");
}
}
}
//异常验证过滤器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace FilterExam.Fiter
{
public class MyException:HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
base.OnException(filterContext);
filterContext.Result = new RedirectResult("/Error/400.html");
}
}
}
//FilterConfig
using FilterExam.Fiter;
using System.Web;
using System.Web.Mvc;
namespace FilterExam
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
//filters.Add(new HandleErrorAttribute());
//filters.Add(new MyAuthorization());
filters.Add(new MyException());
}
}
}
<system.web>
<customErrors mode="On"></customErrors>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
</system.web>