을 만드는 방법을 모두 잡아로 취급하'404 페이지를 찾을 수 없습니다.'라는 쿼리 ASP.NET MVC?
-
10-07-2019 - |
문제
를 만드는 것이 가능합니다 최종 경로를 잡는 모든..튀는 사용자를 404 에서 보기 ASP.NET MVC?
참고:나는 원하지 않는 이 설정을 내 IIS 설정합니다.
해결책
답을 직접 찾았습니다.
리차드 딩 월 다양한 전략을 거치는 훌륭한 게시물이 있습니다. 나는 특히 Filterattribute 솔루션을 좋아합니다. 나는 Willy Nilly 주변에 예외를 던지는 팬이 아니므로 개선 할 수 있는지 확인하겠습니다 :)
Global.asax의 경우이 코드를 마지막 경로로 추가하십시오. 등록하십시오.
routes.MapRoute(
"404-PageNotFound",
"{*url}",
new { controller = "StaticContent", action = "PageNotFound" }
);
다른 팁
이 질문은 먼저 나왔지만 더 쉬운 답변은 나중에 질문에 나왔습니다.
사용자 정의 ASP.NET MVC 404 오류 페이지 라우팅
이 기사의 뷰를 반환하는 ErrorController를 만들어 오류 처리를 받았습니다. 또한 Global.asax의 경로에 "Catch All"을 추가해야했습니다.
Web.config ..에 있지 않으면이 오류 페이지가 어떻게 얻을 수 있는지 알 수 없습니다. 내 web.config는 다음을 지정해야했습니다.
customErrors mode="On" defaultRedirect="~/Error/Unknown"
그리고 나서 나는 또한 다음을 추가했다.
error statusCode="404" redirect="~/Error/NotFound"
도움이 되었기를 바랍니다.
나는 너무 간단하기 때문에 지금 이런 식으로 좋아합니다.
<customErrors mode="On" defaultRedirect="~/Error/" redirectMode="ResponseRedirect">
<error statusCode="404" redirect="~/Error/PageNotFound/" />
</customErrors>
또한 당신은 처리할 수 있습을 발견하지 않에 오류가 글로벌입니다.맨.cs 아래와 같이
protected void Application_Error(object sender, EventArgs e)
{
Exception lastErrorInfo = Server.GetLastError();
Exception errorInfo = null;
bool isNotFound = false;
if (lastErrorInfo != null)
{
errorInfo = lastErrorInfo.GetBaseException();
var error = errorInfo as HttpException;
if (error != null)
isNotFound = error.GetHttpCode() == (int)HttpStatusCode.NotFound;
}
if (isNotFound)
{
Server.ClearError();
Response.Redirect("~/Error/NotFound");// Do what you need to render in view
}
}
프로젝트 루트 web.config 파일 아래 에이 줄을 추가하십시오.
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" />
<error statusCode="404" responseMode="ExecuteURL" path="/Test/PageNotFound" />
<remove statusCode="500" />
<error statusCode="500" responseMode="ExecuteURL" path="/Test/PageNotFound" />
</httpErrors>
<modules>
<remove name="FormsAuthentication" />
</modules>
이것은 당신이 사용할 때 문제 일 수 있습니다
throw new HttpException(404);
당신이 그것을 잡고 싶을 때, 나는 당신의 웹 구성을 편집 한 다음 다른 방법을 모른다.
캐치-모든 경로를 만드는 대안은 Application_EndRequest
당신의 방법 MvcApplication
당 마르코의 더 나은 유니콘 MVC 404 답변.
내부에 RouterConfig.cs
Follwing 코드를 추가하십시오.
routes.MapRoute(
name: "Error",
url: "{id}",
defaults: new
{
controller = "Error",
action = "PageNotFound"
});
경로를 해결할 수없는 경우 MVC 프레임 워크는 404 오류를 통해입니다. 가장 좋은 방법은 예외 필터를 사용하는 것입니다 ... 사용자 정의 예외 필터를 만들고 이렇게 만들 수 있습니다.
public class RouteNotFoundAttribute : FilterAttribute, IExceptionFilter {
public void OnException(ExceptionContext filterContext) {
filterContext.Result = new RedirectResult("~/Content/RouteNotFound.html");
}
}