在MVC中获取响应内容

本文关键字:响应 获取 MVC | 更新日期: 2023-09-27 18:06:39

我正在为我的MVC 4应用程序实现一个错误处理程序。
现在我正在做同样的所有错误,而不仅仅是404,我想得到原始的响应,以保存它的日志记录或显示它,如果在调试模式,因为它包括有用的信息,如完整的堆栈跟踪,小显示在代码中错误发生的地方等等。

我现在正在努力在调用Response.Clear()之前从Response对象中获得缓冲响应数据,但无法弄清楚如何。

我怎么能得到一个HttpResonse对象的内容?

对于HttpWebResponse,有一个GetResponseStream()方法可以用于此,在那里我发现了很多例子,但没有HttpResonseOutputStream无法读取…

在MVC中获取响应内容

不确定这是否有助于正确的方向,但我只是使用这个:

[AttributeUsage(AttributeTargets.Class)]
public class ErrorHandlerAttribute : FilterAttribute, IExceptionFilter
{
    readonly BaseController _bs = new BaseController();
    public virtual void OnException(ExceptionContext fc)
    {
        var model = new errors
        {
            stacktrace = fc.Exception.StackTrace,
            url = fc.HttpContext.Request.RawUrl,
            controller = fc.RouteData.GetRequiredString("controller"),
            source = fc.Exception.Source,
            errordate = DateTime.Now,
            message = fc.Exception.Message//,
            //InnExc = String.IsNullOrEmpty(fc.Exception.InnerException.ToString()) ? fc.Exception.InnerException.ToString() : ""
        };
        var message = "<html><head></head><body><h2>An error occured on " + _bs.GetKeyValue<string>("Mobile Chat App") + ".</h2>";
        message += "<strong>Message:</strong> <pre style='"background-color:#FFFFEF'"> " + model.message + "</pre><br />";
        message += "<strong>Source:</strong> <pre style='"background-color:#FFFFEF'">" + model.source + "</pre><br />";
        message += "<strong>Stacktrace:</strong><pre style='"background-color:#FFFFEF'"> " + model.stacktrace + "</pre><br />";
        message += "<strong>Raw URL:</strong> <pre style='"background-color:#FFFFEF'">" + model.url + "</pre></br />";
        message += "<strong>Inner Exception:</strong> <pre style='"background-color:#FFFFEF'">" + model.InnExc + "</pre></br />";
        message += "<strong>Any Form values</strong>: <pre>" + fc.HttpContext.Request.Form + "</pre><br />";
        message += "</body></html>";
        fc.ExceptionHandled = true;
        fc.HttpContext.Response.Clear();
        fc.HttpContext.Response.StatusCode = 500;
        fc.HttpContext.Response.TrySkipIisCustomErrors = true;
        _bs.SendErrorMail(message);
        fc.ExceptionHandled = true;
        //var res = new ViewResult { ViewName = "error" };
        //fc.Result = res;
        fc.HttpContext.Response.Redirect("/ErrorPage");
        //fc.HttpContext.Response.RedirectToRoute("error",new{controller="Home",action="ErrorPage"});
    }

我有一个gmail错误帐户,我把所有的错误扔进去,并让我知道如果任何网站我做错了,这还没有失败我的信息。我没有深入研究过这个问题,因为我最近使用了一种不同的方法,但是:

fc.HttpContext.Request.RawUrl, 

只是httpContext,你有httpContext的hold,我使用get和fc.HttpContext.Request.Form的URL来获取任何和所有可能导致错误的表单数据。

这不是你所要求的响应,但这是因为我在请求期间捕获错误,而不是响应错误!!然后我清除响应(将是一个错误500),并将其替换为重定向到我的页面,该页面有一个带键盘的猴子的漂亮图片:-)