Returning a specific action result from a request filter
I have a Filter Attribute registred globally in my MVC app that checks for a specific configuration based on a url. I plan to use a catchall in IIS so for domains that don't match, I want to display a 404 page without redirecting first.
So far I have:
public class GetWebsiteConfiguration : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
string siteNoteFoundName = "SiteNotFound";
string controllerName = "Error";
if (filterContext.ActionDescriptor.ActionName != siteNoteFoundName && filterContext.ActionDescriptor.ControllerDescriptor.ControllerName != controllerName)
{
//Code removed for brevity
IWebsiteService websiteSvc = new WebsiteService();
Website website = websiteSvc.GetByDomain(HttpContext.Current.Request.Url.Host);
if (website != null)
{
//load up the website's config - e.g. asset code etc.
}
else
{
//this is where I'm stuck - I want to return my action result SiteNotFound in my
//controller Error as the filterContext.Result.
//filterContext.Result = ??
}
}
}
}
However, I can't figure out what to set filterContext.Result to. I tried controller.Execute() but that rendered the original page being requested, as well as the not found page. I know I can do a redirectResult, but I'd rather not...
Thanks in advance.
One way would be to create a base controller and move the SiteNotFound action in there.
public class BaseController : Controller {
protected HttpNotFoundResult SiteNotFound(string statusDescription = null)
{
return new HttpNotFoundResult(statusDescription);
}
}
Then you can simply assign the result as:
filterContext.Result = filterContext.Controller.SiteNotFound(<description>);
You also may want to set this (to avoid IIS into catching those errors)
controllerContext.HttpContext.Response.TrySkipIisCustomErrors = true;
链接地址: http://www.djcxy.com/p/74438.html
上一篇: 在MVC 5中使用自定义ActionFilterAttribute注销用户
下一篇: 从请求过滤器返回特定的操作结果