c# – 404异常时更新视图
发布时间:2020-12-15 22:12:06 所属栏目:百科 来源:网络整理
导读:在我的代码上我使用log4net来记录异常并结束日志记录我想用适当的消息视图更新视图.在我的日志服务更新视图(实际上我的代码重定向)我的代码看起来像这样 private readonly HttpContextBase _httpContext;public void RedirectToError(){ var httpException =
在我的代码上我使用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? 谢谢 解决方法
目前还不清楚第一个代码块的位置以及第二个块是否与您的问题相关(除了演示).你的问题不清楚,所以这是在黑暗中拍摄的.
将信息从应用程序的一个部分传递到另一个部分的一种方法是使用请求缓存. 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(); } 通常,您只需记录错误,而不是将其显示给用户,因为可能存在安全隐患. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |