我在我的MVC应用程序中全局注册了一个过滤器属性,该应用程序根据URL检查特定配置。我计划在IIS中使用catchall,因此对于不匹配的域,我想显示404页面而不首先重定向。
到目前为止,我有:
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 = ??
}
}
}
}
但是,我无法弄清楚要将filterContext.Result设置为什么。我尝试了controller.Execute(),但是它呈现了所请求的原始页面,以及未找到的页面。我知道我可以做一个redirectResult,但我宁愿不...
提前致谢。
答案 0 :(得分:0)
一种方法是创建一个基本控制器并在那里移动SiteNotFound操作。
public class BaseController : Controller {
protected HttpNotFoundResult SiteNotFound(string statusDescription = null)
{
return new HttpNotFoundResult(statusDescription);
}
}
然后您可以简单地将结果指定为:
filterContext.Result = filterContext.Controller.SiteNotFound(<description>);
您也可能想要设置此项(以避免IIS捕获这些错误)
controllerContext.HttpContext.Response.TrySkipIisCustomErrors = true;