微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 404异常时更新视图

在我的代码上我使用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无法做到这一点我们怎么能实现这个呢?

谢谢

解决方法

目前还不清楚第一个代码块的位置以及第二个块是否与您的问题相关(除了演示).你的问题不清楚,所以这是在黑暗中拍摄的.

将信息从应用程序的一个部分传递到另一个部分的一种方法是使用请求缓存.

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();
}

通常,您只需记录错误,而不是将其显示用户,因为可能存在安全隐患.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐