在我的代码中,我使用log4net来记录异常并结束日志记录我想用适当的消息视图更新视图。在我的日志服务更新视图(实际上我的代码重定向)我的代码看起来像这样
private readonly HttpContextBase _httpContext;
public void RedirectToError()
{
var httpException = _httpContext.Server.GetLastError();
if (httpException != null && (_httpContext.Server.GetLastError() is HttpException))
{
_httpContext.Server.ClearError();
_httpContext.Response.Redirect("/Error", false);
}
}
但我真的想更新viewresult只是像授权属性我能够像这样更新viewresult
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Result = new ViewResult {ViewName = "NoPermissions"};
}
else
{
// let the base implementation redirect the user
base.HandleUnauthorizedRequest(filterContext);
}
}
但也不像filtercontext,我们如何用httpcontext更新viewresult? 如果用httpcontext无法做到这一点我们怎么能实现这个呢?
由于
答案 0 :(得分:1)
目前还不清楚第一个代码块的位置以及第二个块是否与您的问题(演示除外)有关。你的问题不清楚,所以这是在黑暗中拍摄的。
将信息从应用程序的一个部分传递到另一个部分的一种方法是使用请求缓存。
private readonly HttpContextBase _httpContext;
public void RedirectToError()
{
var httpException = _httpContext.Server.GetLastError();
if (httpException != null && (_httpContext.Server.GetLastError() is HttpException))
{
_httpContext.Server.ClearError();
// Store the error in the request cache
_httpContext.Items["LastError"] = httpException;
_httpContext.Response.Redirect("/Error", false);
}
}
然后在您的错误操作方法中,您可以访问此值。
public ActionResult Error()
{
// Retrieve the error from the request cache
Exception lastError = (Exception)this.HttpContext.Items["lastError"];
// Pass the error message to the view
ViewBag.Error = lastError.Message;
return View();
}
通常情况下,您只需记录错误,而不是将其显示给用户,因为可能存在安全隐患。
答案 1 :(得分:0)
您可以在Global.asax中的Application_Error方法中捕获错误,并使用HttpContext重定向到您的页面。
Protected void Application_Error(object sender, EventArgs e)
{
MvcApplication app = (MvcApplication)sender;
HttpContext context = app.Context;
Exception exc = Server.GetLastError();
if (exc.GetType() == typeof(HttpException))
{
errorCode = ((HttpException)exc).GetHttpCode();
}
else if (exc.GetType() == typeof(Exception))
{
errorCode = 500;
}
var routeData = new RouteData();
routeData.Values["controller"] = "{Your Controller}";
routeData.Values["statusDescription"] = "{Your Description}";
routeData.Values["action"] = "http500";
switch (errorCode)
{
case 404:
Server.ClearError();
routeData.Values["action"] = "Your action name";
break;
case 403:
Server.ClearError();
routeData.Values["action"] = "Your action name";
break;
case 405:
Server.ClearError();
routeData.Values["action"] = "Your action name";
break;
case 500:
Server.ClearError();
routeData.Values["action"] = "Your action name";
break;
default:
Server.ClearError();
routeData.Values["action"] = "Your action name";
break;
}
IController controller = new ErrorsController();
controller.Execute(new RequestContext(new HttpContextWrapper(context), routeData));
Server.ClearError();
}
如果有帮助,请回复。 :)
答案 2 :(得分:0)
看起来你试图在显示错误页面之前避免使用302并且只返回带有错误的404 ...
如果你得到一个返回ViewResult的控制器方法,那么你已经超过了ASP.NET确定它应该返回404的点。