ASP에서 사용자 정의 오류 페이지를 작동시키는 방법.NET MVC 4
저는 500, 404, 403에 대한 커스텀 에러 페이지를 원합니다.제가 한 일은 다음과 같습니다.
다음과 같이 web.config에서 사용자 지정 오류를 활성화했습니다.
<customErrors mode="On" defaultRedirect="~/Views/Shared/Error.cshtml"> <error statusCode="403" redirect="~/Views/Shared/UnauthorizedAccess.cshtml" /> <error statusCode="404" redirect="~/Views/Shared/FileNotFound.cshtml" /> </customErrors>HandleErrorAttribute의 글로벌FilterConfig클래스는 다음과 같습니다.public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new CustomHandleErrorAttribute()); filters.Add(new AuthorizeAttribute()); }위의 각 메시지에 대한 사용자 지정 오류 페이지를 만들었습니다.500의 기본값은 이미 개봉 후 사용할 수 있었습니다.
각 사용자 정의 오류 페이지 보기에서 페이지에 대한 모델이 다음과 같이 선언되었습니다.
System.Web.Mvc.HandleErrorInfo
500의 경우 사용자 정의 오류 페이지가 표시됩니다.다른 사람들에게는 그렇지 않습니다.
제가 놓친 게 있나요?
코드를 읽어보니 사용자 지정 오류가 표시되는 것은 이뿐만이 아닌 것 같습니다.OnException의 HandleErrorAttribute클래스 그리고 그것은 단지 500을 다루고 있습니다.
다른 오류를 처리하려면 어떻게 해야 합니까?
대한 되는 것 은 현재설(MVC3 에적것은같다니습정는다니사합용되용기을능다음같은과전히여만지있은▁an▁mymv▁having)▁(다에▁on▁relies현▁applies니사,재)설▁mv합on▁setup▁current▁it▁think용▁i▁but▁stillc다ErrorController그래서 나는 사용합니다.
<system.web>
<customErrors mode="On" defaultRedirect="~/Error">
<error redirect="~/Error/NotFound" statusCode="404" />
</customErrors>
</system.web>
컨트롤러에는 다음이 포함됩니다.
public class ErrorController : Controller
{
public ViewResult Index()
{
return View("Error");
}
public ViewResult NotFound()
{
Response.StatusCode = 404; //you may want to set this to 200
return View("NotFound");
}
}
그리고 그 관점들은 당신이 그것들을 실행하는 방식과 같습니다.그러나 응용 프로그램이 디버그 모드에 있을 경우 스택 추적 및 오류 정보를 표시하기 위해 약간의 논리를 추가하는 경향이 있습니다.Error.cshtml은 다음과 같습니다.
@model System.Web.Mvc.HandleErrorInfo
@{
Layout = "_Layout.cshtml";
ViewBag.Title = "Error";
}
<div class="list-header clearfix">
<span>Error</span>
</div>
<div class="list-sfs-holder">
<div class="alert alert-error">
An unexpected error has occurred. Please contact the system administrator.
</div>
@if (Model != null && HttpContext.Current.IsDebuggingEnabled)
{
<div>
<p>
<b>Exception:</b> @Model.Exception.Message<br />
<b>Controller:</b> @Model.ControllerName<br />
<b>Action:</b> @Model.ActionName
</p>
<div style="overflow:scroll">
<pre>
@Model.Exception.StackTrace
</pre>
</div>
</div>
}
</div>
파블로 솔루션을 했고 항상 오류가 있었습니다 (MVC4)
'Error' 보기 또는 해당 마스터를 찾을 수 없거나 검색된 위치를 지원하는 보기 엔진이 없습니다.
이를 제거하려면 라인을 제거합니다.
filters.Add(new HandleErrorAttribute());
FilterConfig.cs 에서
저는 게시된 다른 솔루션보다 코딩이 덜 필요한 작업을 수행합니다.
먼저 web.config에는 다음과 같은 기능이 있습니다.
<customErrors mode="On" defaultRedirect="~/ErrorPage/Oops">
<error redirect="~/ErrorPage/Oops/404" statusCode="404" />
<error redirect="~/ErrorPage/Oops/500" statusCode="500" />
</customErrors>
컨트롤러(/Controllers/ErrorPageController.cs )에는 다음이 포함되어 있습니다.
public class ErrorPageController : Controller
{
public ActionResult Oops(int id)
{
Response.StatusCode = id;
return View();
}
}
마지막으로, 보기에는 다음이 포함됩니다(간단하게 하기 위해 삭제되었지만 포함될 수 있음).
@{ ViewBag.Title = "Oops! Error Encountered"; }
<section id="Page">
<div class="col-xs-12 well">
<table cellspacing="5" cellpadding="3" style="background-color:#fff;width:100%;" class="table-responsive">
<tbody>
<tr>
<td valign="top" align="left" id="tableProps">
<img width="25" height="33" src="~/Images/PageError.gif" id="pagerrorImg">
</td>
<td width="360" valign="middle" align="left" id="tableProps2">
<h1 style="COLOR: black; FONT: 13pt/15pt verdana" id="errortype"><span id="errorText">@Response.Status</span></h1>
</td>
</tr>
<tr>
<td width="400" colspan="2" id="tablePropsWidth"><font style="COLOR: black; FONT: 8pt/11pt verdana">Possible causes:</font>
</td>
</tr>
<tr>
<td width="400" colspan="2" id="tablePropsWidth2">
<font style="COLOR: black; FONT: 8pt/11pt verdana" id="LID1">
<hr>
<ul>
<li id="list1">
<span class="infotext">
<strong>Baptist explanation: </strong>There
must be sin in your life. Everyone else opened it fine.<br>
</span>
</li>
<li>
<span class="infotext">
<strong>Presbyterian explanation: </strong>It's
not God's will for you to open this link.<br>
</span>
</li>
<li>
<span class="infotext">
<strong> Word of Faith explanation:</strong>
You lack the faith to open this link. Your negative words have prevented
you from realizing this link's fulfillment.<br>
</span>
</li>
<li>
<span class="infotext">
<strong>Charismatic explanation: </strong>Thou
art loosed! Be commanded to OPEN!<br>
</span>
</li>
<li>
<span class="infotext">
<strong>Unitarian explanation:</strong> All
links are equal, so if this link doesn't work for you, feel free to
experiment with other links that might bring you joy and fulfillment.<br>
</span>
</li>
<li>
<span class="infotext">
<strong>Buddhist explanation:</strong> .........................<br>
</span>
</li>
<li>
<span class="infotext">
<strong>Episcopalian explanation:</strong>
Are you saying you have something against homosexuals?<br>
</span>
</li>
<li>
<span class="infotext">
<strong>Christian Science explanation: </strong>There
really is no link.<br>
</span>
</li>
<li>
<span class="infotext">
<strong>Atheist explanation: </strong>The only
reason you think this link exists is because you needed to invent it.<br>
</span>
</li>
<li>
<span class="infotext">
<strong>Church counselor's explanation:</strong>
And what did you feel when the link would not open?
</span>
</li>
</ul>
<p>
<br>
</p>
<h2 style="font:8pt/11pt verdana; color:black" id="ietext">
<img width="16" height="16" align="top" src="~/Images/Search.gif">
HTTP @Response.StatusCode - @Response.StatusDescription <br>
</h2>
</font>
</td>
</tr>
</tbody>
</table>
</div>
</section>
그것은 그것만큼 간단합니다.더 자세한 오류 정보를 제공하기 위해 쉽게 확장될 수 있지만 ELMAH는 저를 위해 그것을 처리하고 Code & statusDescription은 제가 보통 필요로 하는 모든 것입니다.
여기에는 여러 단계가 뒤섞여 있는 것 같습니다.처음부터 제가 한 일을 내세울 것입니다.
다음을 생성합니다.
ErrorPagepublic class ErrorPageController : Controller { public ActionResult Index() { return View(); } public ActionResult Oops(int id) { Response.StatusCode = id; return View(); } }이 두 가지 작업에 대한 보기를 추가합니다(오른쪽 클릭 -> 보기 추가).이러한 폴더는 ErrorPage라는 폴더에 표시되어야 합니다.
에 안에.
App_Start열어 보세요.FilterConfig.cs오류 처리 필터를 설명합니다.public static void RegisterGlobalFilters(GlobalFilterCollection filters) { // Remove this filter because we want to handle errors ourselves via the ErrorPage controller //filters.Add(new HandleErrorAttribute()); }에 다음 web.config 파일을 합니다.
<customerErrors>목항, 래아 아래에 있습니다.System.Web<customErrors mode="On" defaultRedirect="~/ErrorPage/Oops"> <error redirect="~/ErrorPage/Oops/404" statusCode="404" /> <error redirect="~/ErrorPage/Oops/500" statusCode="500" /> </customErrors>테스트(물론).코드에 처리되지 않은 예외를 던져 ID가 500인 페이지로 이동한 다음 존재하지 않는 페이지의 URL을 사용하여 404를 확인합니다.
Global.asax.cs 파일을 사용하는 것을 추천합니다.
protected void Application_Error(Object sender, EventArgs e)
{
var exception = Server.GetLastError();
if (exception is HttpUnhandledException)
{
Server.Transfer("~/Error.aspx");
}
if (exception != null)
{
Server.Transfer("~/Error.aspx");
}
try
{
// This is to stop a problem where we were seeing "gibberish" in the
// chrome and firefox browsers
HttpApplication app = sender as HttpApplication;
app.Response.Filter = null;
}
catch
{
}
}
maxspan이 올린 답변을 바탕으로 GitHub에 모든 작업 부분을 보여주는 최소한의 샘플 프로젝트를 작성했습니다.
기본적으로, 우리는 단지 추가할 뿐입니다.Application_Error메소드를 global.asax.cs 에 제공하여 예외를 가로채고 사용자 정의 오류 페이지로 리디렉션(또는 보다 정확하게 전송 요청)할 수 있습니다.
protected void Application_Error(Object sender, EventArgs e)
{
// See http://stackoverflow.com/questions/13905164/how-to-make-custom-error-pages-work-in-asp-net-mvc-4
// for additional context on use of this technique
var exception = Server.GetLastError();
if (exception != null)
{
// This would be a good place to log any relevant details about the exception.
// Since we are going to pass exception information to our error page via querystring,
// it will only be practical to issue a short message. Further detail would have to be logged somewhere.
// This will invoke our error page, passing the exception message via querystring parameter
// Note that we chose to use Server.TransferRequest, which is only supported in IIS 7 and above.
// As an alternative, Response.Redirect could be used instead.
// Server.Transfer does not work (see https://support.microsoft.com/en-us/kb/320439 )
Server.TransferRequest("~/Error?Message=" + exception.Message);
}
}
오류 컨트롤러:
/// <summary>
/// This controller exists to provide the error page
/// </summary>
public class ErrorController : Controller
{
/// <summary>
/// This action represents the error page
/// </summary>
/// <param name="Message">Error message to be displayed (provided via querystring parameter - a design choice)</param>
/// <returns></returns>
public ActionResult Index(string Message)
{
// We choose to use the ViewBag to communicate the error message to the view
ViewBag.Message = Message;
return View();
}
}
오류 페이지 보기:
<!DOCTYPE html>
<html>
<head>
<title>Error</title>
</head>
<body>
<h2>My Error</h2>
<p>@ViewBag.Message</p>
</body>
</html>
비활성화/제거 외에는 다른 관련 사항이 없습니다.filters.Add(new HandleErrorAttribute())FilterConfig.cs 에서
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
//filters.Add(new HandleErrorAttribute()); // <== disable/remove
}
}
구현이 매우 간단하지만 이 접근 방식에서 한 가지 단점은 쿼리 문자열을 사용하여 대상 오류 페이지에 예외 정보를 전달하는 것입니다.
모든 것을 설정했지만 로컬 개발 서버에서 모든 것이 정상적으로 작동했음에도 불구하고 스테이징 서버에서 상태 코드 500에 대한 오류 페이지를 제대로 볼 수 없었습니다.
저는 릭 스트렐의 블로그 게시물을 발견했습니다. 그것은 저에게 도움이 되었습니다.
는 추해야했다니를 추가해야 했습니다.Response.TrySkipIisCustomErrors = true;사용자 지정 오류 처리 코드로.
여기 제 해결책이 있습니다.[ExportModelStateToTempData] / [ImportModelStateFromTempData]를 사용하는 것이 불편하다고 생각합니다.
~/Views/Home/Error.cshtml:
@{
ViewBag.Title = "Error";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Error</h2>
<hr/>
<div style="min-height: 400px;">
@Html.ValidationMessage("Error")
<br />
<br />
<button onclick="Error_goBack()" class="k-button">Go Back</button>
<script>
function Error_goBack() {
window.history.back()
}
</script>
</div>
~/컨트롤러/HomeController.sc :
public class HomeController : BaseController
{
public ActionResult Index()
{
return View();
}
public ActionResult Error()
{
return this.View();
}
...
}
~/컨트롤러/BaseController.sc :
public class BaseController : Controller
{
public BaseController() { }
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.Result is ViewResult)
{
if (filterContext.Controller.TempData.ContainsKey("Error"))
{
var modelState = filterContext.Controller.TempData["Error"] as ModelState;
filterContext.Controller.ViewData.ModelState.Merge(new ModelStateDictionary() { new KeyValuePair<string, ModelState>("Error", modelState) });
filterContext.Controller.TempData.Remove("Error");
}
}
if ((filterContext.Result is RedirectResult) || (filterContext.Result is RedirectToRouteResult))
{
if (filterContext.Controller.ViewData.ModelState.ContainsKey("Error"))
{
filterContext.Controller.TempData["Error"] = filterContext.Controller.ViewData.ModelState["Error"];
}
}
base.OnActionExecuted(filterContext);
}
}
~/컨트롤러/MyController.sc :
public class MyController : BaseController
{
public ActionResult Index()
{
return View();
}
public ActionResult Details(int id)
{
if (id != 5)
{
ModelState.AddModelError("Error", "Specified row does not exist.");
return RedirectToAction("Error", "Home");
}
else
{
return View("Specified row exists.");
}
}
}
성공적인 프로젝트 되시길 바랍니다 ;-)
global.cs 을 해킹하거나 HandleErrorAttribute를 조작하거나 Response를 수행하지 않고도 오류가 올바르게 작동할 수 있습니다.TrySkipIisCustomErrors, application_Errors를 후크하거나 다음 중 하나를 수행합니다.
시스템에서.웹(일반적인 설정/해제만 가능)
<customErrors mode="On">
<error redirect="/error/401" statusCode="401" />
<error redirect="/error/500" statusCode="500" />
</customErrors>
그리고 체계적으로.웹 서버
<httpErrors existingResponse="PassThrough" />
이제 모든 것이 예상대로 작동하고 오류 컨트롤러를 사용하여 필요한 항목을 표시할 수 있습니다.
web.config에서 시스템 아래에 이를 추가합니다.아래와 같은 웹 서버 태그,
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404"/>
<remove statusCode="500"/>
<error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound"/>
<error statusCode="500" responseMode="ExecuteURL"path="/Error/ErrorPage"/>
</httpErrors>
컨트롤러를 다음과 같이 추가합니다.
public class ErrorController : Controller
{
//
// GET: /Error/
[GET("/Error/NotFound")]
public ActionResult NotFound()
{
Response.StatusCode = 404;
return View();
}
[GET("/Error/ErrorPage")]
public ActionResult ErrorPage()
{
Response.StatusCode = 500;
return View();
}
}
그리고 그들의 존경하는 견해를 더하면, 이것은 분명히 모두에게 효과가 있을 것이라고 생각합니다.
이 솔루션은 다음과 같습니다.해왕성 세기
제가 파티에 늦게 온 것 같은데, 당신도 이것을 확인하는 것이 좋겠습니다.
소인system.web반환 HttpNotFound()와 같은 응용 프로그램 내의 예외를 캐싱하는 경우
<system.web>
<customErrors mode="RemoteOnly">
<error statusCode="404" redirect="/page-not-found" />
<error statusCode="500" redirect="/internal-server-error" />
</customErrors>
</system.web>
그리고.system.webServerIIS에 의해 잡히고 asp.net 프레임워크에 도달하지 못한 오류를 따라잡기 위해.
<system.webServer>
<httpErrors errorMode="DetailedLocalOnly">
<remove statusCode="404"/>
<error statusCode="404" path="/page-not-found" responseMode="Redirect"/>
<remove statusCode="500"/>
<error statusCode="500" path="/internal-server-error" responseMode="Redirect"/>
</system.webServer>
마지막으로, 고객의 반응이 걱정되는 경우에는 다음을 변경합니다.responseMode="Redirect"로.responseMode="File"정적 html 파일을 제공합니다. 이 파일은 200개의 응답 코드가 있는 친숙한 페이지를 표시하기 때문입니다.
언급URL : https://stackoverflow.com/questions/13905164/how-to-make-custom-error-pages-work-in-asp-net-mvc-4
'programing' 카테고리의 다른 글
| 동일한 문서의 필드가 있는 Mongodb 쿼리 (0) | 2023.05.04 |
|---|---|
| Postgresql 스키마 경로 영구 설정 (0) | 2023.05.04 |
| postgres에서 중복 어레이 값 제거 (0) | 2023.05.04 |
| bash 셸 스크립트에 파일을 포함하는 방법 (0) | 2023.05.04 |
| 파이썬 3의 수율 생성기에는 next() 함수가 없습니다. (0) | 2023.05.04 |