我已经构建了一个很好的 MVC4 应用程序,决定保护它,一切都很好。下面是我用来帮助防止 XSS 攻击的过滤器的示例。
public class IsPostedFromThisSiteAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
//TODO: - Possible problems in future:
//1. Is there a way to handle the execptions and just display a friendly error page / message.
if (filterContext.HttpContext != null)
{
if (filterContext.HttpContext.Request.UrlReferrer == null)
throw new System.Web.HttpException("Invalid Submission");
//if (filterContext.HttpContext.Request.UrlReferrer.Host != "localhost/YeatsClinical.PatientPortal.Web")
if (filterContext.HttpContext.Request.UrlReferrer.AbsolutePath != ConfigurationManager.AppSettings["SiteURL"])
throw new System.Web.HttpException("This form was not submitted from this site!");
}
}
}
我的 MVC 应用程序安装了 Elmah,并且效果也很好。
问题是,我知道上面的错误,但我不想显示异常消息,或记录它或类似的东西(所有这些我都可以轻松完成)。相反,我想通过向用户显示一条漂亮的小消息来正确处理它。如何更改上面的代码,以允许显示 View 或部分 View 并带有一条漂亮的小消息,或者只是在某处输出一些文本,让用户以一种不会导致应用程序崩溃的好方式知道出了什么问题,也许在这种特殊情况下,让他返回到正确的登录屏幕。
最佳答案
只需在 filterContext
上分配 Result
属性即可:
public class IsPostedFromThisSiteAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
//TODO: - Possible problems in future:
//1. Is there a way to handle the execptions and just display a friendly error page / message.
if (filterContext.HttpContext != null)
{
if (filterContext.HttpContext.Request.UrlReferrer == null)
{
var viewResult = new ViewResult
{
ViewName = "~/Views/Shared/Invalid.cshtml"
};
filterContext.Result = viewResult;
return;
}
if (filterContext.HttpContext.Request.UrlReferrer.AbsolutePath != ConfigurationManager.AppSettings["SiteURL"])
{
var viewResult = new ViewResult
{
ViewName = "~/Views/Shared/InvalidSite.cshtml"
};
filterContext.Result = viewResult;
return;
}
}
}
}
这将阻止执行 Controller 操作,并立即执行您分配给 filterContext
的 Result
属性的 ActionResult
。基本上,您正在短路操作的执行。您可以返回任何您想要的 ActionResult:ViewResult、PartialViewResult、JsonResult、RedirectToRouteResult,...
关于c# - 使用安装在 ASP.NET MVC 4 应用程序中的 Elmah 进行异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14625246/