gpt4 book ai didi

c# - 在 MVC 中获取响应内容

转载 作者:太空宇宙 更新时间:2023-11-03 13:44:49 28 4
gpt4 key购买 nike

我在 THIS 之后为我的 MVC 4 应用程序实现错误处理程序.
现在我对所有错误都做同样的事情,不仅是 404,而且我想获得原始响应以保存它以进行日志记录或在 Debug模式下显示它,因为它包含有用的信息,如完整的堆栈跟踪、小显示发生错误的代码等等。

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

如何获取 HttpResonse 对象的内容?

对于 HttpWebResponse有一个GetResponseStream()可以用于此的方法,我在其中找到了很多示例,但没有用于 HttpResonseOutputStream无法读取...

最佳答案

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

[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,我使用 URL 获取和 fc.HttpContext.Request.Form 来获取可能导致错误的所有表单数据。

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

关于c# - 在 MVC 中获取响应内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15735105/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com