gpt4 book ai didi

C# MVC 错误处理 IIS Express 和 IIS 7.5

转载 作者:行者123 更新时间:2023-11-30 17:38:30 25 4
gpt4 key购买 nike

是否存在真正处理 IIS Express 和 IIS 7.5 上的 404、500 等错误的完整解决方案?

我已经记不清我读了多少文章,关于 Web.config、打开、关闭 customErrors 等...或评论/取消评论 filters.Add(new HandleErrorAttribute());来自 FilterConfig.cs

有人可以回顾一下我目前的情况并告诉我正确的配置是什么使我能够在 IIS Express 和 IIS 7.5 上完全捕获服务器错误,显示自定义错误页面而不是 Shared/Error.cshtml似乎无论如何都会被调用,而 Application_Error 会被忽略。

Global.asax.cs

protected void Application_Error(object sender, EventArgs e)
{
var lastError = Server.GetLastError();

Server.ClearError();

var statusCode = lastError.GetType() == typeof(HttpException) ? ((HttpException)lastError).GetHttpCode() : 500;

var httpContextWrapper = new HttpContextWrapper(Context);

var routeData = new RouteData();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("action", "Index");
routeData.Values.Add("statusCode", statusCode);
routeData.Values.Add("exception", lastError);

IController errorController = new ErrorController();

var requestContext = new RequestContext(httpContextWrapper, routeData);

errorController.Execute(requestContext);

Response.End();
}

ErrorController.cs

public class ErrorController : Controller
{
private readonly Common _cf = new Common();
private readonly string _httpReferer = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_REFERER"];
private readonly string _httpUserAgent = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"];

public ActionResult Index(int? statusCode, Exception exception)
{
Response.TrySkipIisCustomErrors = true;

try
{
Response.StatusCode = ((HttpException) exception).GetHttpCode();
}
catch (Exception tryException)
{
SendEmail(tryException, statusCode.ToString());

return Redirect("/");
}

SendEmail(exception, Convert.ToString(Response.StatusCode));

ViewBag.Title = statusCode == 404 ? "Page Not Found" : "Server Error";

ViewBag.ExceptionMessage = Convert.ToString(exception.Message);

return View("Index");
}

private void SendEmail(Exception exception, string errorType)
{
const string to = "to@domain.com";
const string @from = "from@domain.com";

var subject = "SendEmailError (" + errorType + ")";

var stringBuilder = new StringBuilder();
stringBuilder.Append("<p><strong>Exception Message: </strong>" + exception.Message + "</p>");
stringBuilder.Append("<p><strong>Source: </strong>" + exception.Source + "</p>");
stringBuilder.Append("<p><strong>Referer: </strong>" + _httpReferer + "</p>");
stringBuilder.Append("<p><strong>IP Address: </strong>" + _cf.GetIpAddress() + "</p>");
stringBuilder.Append("<p><strong>Browser: </strong>" + _httpUserAgent + "</p>");
stringBuilder.Append("<p><strong>Target: </strong>" + exception.TargetSite + "</p>");
stringBuilder.Append("<p><strong>Stack Trace: </strong>" + exception.StackTrace + "</p>");
stringBuilder.Append("<p><strong>Inner Exception: </strong>" + (exception.InnerException != null ? exception.InnerException.Message : "") + "</p>");

var body = stringBuilder.ToString();

_cf.SendEmail(subject, to, from, body, null, true, null, null);
}
}

Index.cshtml

@model WebApplication1.Models.Error

@if (HttpContext.Current.IsDebuggingEnabled)
{
if (Model != null)
{
<p><strong>Exception:</strong> @Model.Exception.Message</p>
<div style="overflow:scroll">
<pre>@Model.Exception.StackTrace</pre>
</div>
}
else
{
<p><strong>Exception:</strong> @ViewBag.ExceptionMessage</p>
}
}

Error.cs

using System;

namespace WebApplication1.Models
{
public class Error
{
public int HttpStatusCode { get; set; }

public Exception Exception { get; set; }
}
}

任何帮助将不胜感激:-)

最佳答案

刚刚浏览了我最近做的一个项目。我在 Application_Error() 中只有一行:

Exception ex = Server.GetLastError();

FilterConfig.cs

public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
//filters.Add(new HandleErrorAttribute()); // Removed because ELMAH reports "cannot find Shared/Error" view instead of the exception.
}
}

ErrorPageController.cs

public ActionResult DisplayError(int id)
{
if (id == 404)
{
//... you get the idea

Web.config

<customErrors mode="On" defaultRedirect="~/ErrorPage/DisplayError/500">
<error redirect="~/ErrorPage/DisplayError/403" statusCode="403" />
<error redirect="~/ErrorPage/DisplayError/404" statusCode="404" />
<error redirect="~/ErrorPage/DisplayError/500" statusCode="500" />
</customErrors>

在底部我有这个,还有一个方便的评论来提醒自己 :)

<system.webServer>
<handlers>
<add name="ELMAH" verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" preCondition="integratedMode" />
</handlers>
<httpErrors existingResponse="PassThrough" /> <!-- Required for IIS7 to know to serve up the custom error page -->
</system.webServer>

关于C# MVC 错误处理 IIS Express 和 IIS 7.5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36644871/

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