ASP.NET MVC 中田柔,我們通常把身份驗證和通用處理的代碼放在?FilterAttribute 或者?BaseController 中
然后可能會遇到一個問題俐巴,假如你的代碼是:
protected override void OnAuthorization(AuthorizationContext filterContext)
{
var user = GetUser();
if(user == null)
{
filterContext.HttpContext.Response.Redirect("Home");
}
int userID = user.ID;
}
本來Redirect后應該不執(zhí)行下面的代碼,但在MVC中代碼可能會被執(zhí)行硬爆,就會產(chǎn)生 ”未將對象應用設置到實例“的錯誤
所以欣舵,在這個地方,應該使用對應的Redirect方法缀磕,如下:
filterContext.Result = new RedirectResult("Home");
換成這種寫法以后缘圈,后面的代碼就不會執(zhí)行了。
end