사용자 지정 ASP.NET MVC 404 오류 페이지에 대한 라우팅
누군가 일반 "Resource Not Found"ASP.NET 오류를 표시하는 대신 ASP.NET MVC에서 유효한 작업이나 컨트롤러를 호출하지 않는 URL을 입력 할 때 사용자 지정 HTTP 404 오류 페이지를 만들려고합니다.
이것을 처리하기 위해 web.config를 사용하고 싶지 않습니다.
유효하지 않은 URL을 잡기 위해 어떤 종류의 라우팅 마법이 있습니까?
업데이트 : 나는 주어진 대답을 시도했지만 여전히 추악한 "자원을 찾을 수 없습니다"라는 메시지가 나타납니다.
또 다른 업데이트 : 좋아, 분명히 RC1에서 변경된 것이 있습니다. 나는 심지어 404를 덫에 놓으려고 시도했지만 HttpException
여전히 "Resource Not Found"페이지를 제공합니다.
심지어 MvcContrib의 리소스 기능을 사용했지만 동일한 문제는 없습니다. 어떤 아이디어?
경로 테이블 끝에 모든 경로를 잡기 만하면 원하는 모든 페이지가 표시됩니다.
참조 : ASP.NET MVC에 대한 '404 페이지를 찾을 수 없음'쿼리를 처리하기 위해 모든 경로를 잡을 수 있습니까?
프로덕션 서버에서 3 시간 동안 사용자 지정 오류를 활성화하려고 시도했지만 경로없이 ASP.NET MVC 에서이 작업을 수행하는 방법을 최종 해결책으로 찾은 것 같습니다.
ASP.NET MVC 응용 프로그램에서 사용자 지정 오류를 사용하려면 다음이 필요합니다 (IIS 7+).
다음
system.web
섹션의 웹 구성에서 사용자 정의 페이지를 구성 하십시오.<customErrors mode="RemoteOnly" defaultRedirect="~/error"> <error statusCode="404" redirect="~/error/Error404" /> <error statusCode="500" redirect="~/error" /> </customErrors>
RemoteOnly
로컬 네트워크에서 실제 오류가 발생 함을 의미합니다 (개발 중에 매우 유용함). 모든 오류 코드에 대한 오류 페이지를 다시 작성할 수도 있습니다.매직 응답 매개 변수 및 응답 상태 코드 설정 (오류 처리 모듈 또는 오류 핸들 속성)
HttpContext.Current.Response.StatusCode = 500; HttpContext.Current.Response.TrySkipIisCustomErrors = true;
system.webServer
섹션 아래의 웹 설정에서 다른 매직 설정을 지정 하십시오.<httpErrors errorMode="Detailed" />
이것은 내가 찾은 마지막 일이며 프로덕션 서버에서 사용자 정의 오류를 볼 수 있습니다.
이 기사의 뷰를 반환하는 ErrorController를 만들어서 오류 처리가 작동했습니다. 또한 global.asax의 경로에 "Catch All"을 추가해야했습니다.
Web.config ..에 없으면 이러한 오류 페이지가 어떻게 표시되는지 알 수 없습니까? 내 Web.config는 다음을 지정해야했습니다.
customErrors mode="On" defaultRedirect="~/Error/Unknown"
그런 다음 추가했습니다.
error statusCode="404" redirect="~/Error/NotFound"
NotFoundMVC-ASP.NET MVC3 응용 프로그램에서 컨트롤러, 작업 또는 경로를 찾을 수 없을 때마다 사용자에게 친숙한 404 페이지를 제공합니다. 기본 ASP.NET 오류 페이지 대신 NotFound라는보기가 렌더링됩니다.
다음을 사용하여 nuget을 통해이 플러그인을 추가 할 수 있습니다. Install-Package NotFoundMvc
NotFoundMvc는 웹 응용 프로그램 시작 중에 자동으로 설치됩니다. 일반적으로 ASP.NET MVC에서 404 HttpException이 발생하는 모든 다른 방법을 처리합니다. 여기에는 누락 된 컨트롤러, 작업 및 경로가 포함됩니다.
단계별 설치 안내서 :
1-프로젝트를 마우스 오른쪽 버튼으로 클릭하고 Nuget 패키지 관리를 선택하십시오 ...
2-검색하여 NotFoundMvc
설치하십시오.
3-설치가 완료되면 두 개의 파일이 프로젝트에 추가됩니다. 아래 스크린 샷과 같이.
4-새로 추가 된 NotFound.cshtml을 Views / Shared에서 열고 원하는대로 수정하십시오. 이제 응용 프로그램을 실행하고 잘못된 URL을 입력하면 사용하기 쉬운 404 페이지가 나타납니다.
더 이상 사용자에게 다음과 같은 오류 메시지가 표시됩니다 Server Error in '/' Application. The resource cannot be found.
도움이 되었기를 바랍니다 :)
추신 : 멋진 플러그인을 제작 해 주신 Andrew Davey 에게 추천합니다.
Try this in web.config to replace IIS error pages. This is the best solution I guess, and it sends out the correct status code too.
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" subStatusCode="-1" />
<remove statusCode="500" subStatusCode="-1" />
<error statusCode="404" path="Error404.html" responseMode="File" />
<error statusCode="500" path="Error.html" responseMode="File" />
</httpErrors>
</system.webServer>
More info from Tipila - Use Custom Error Pages ASP.NET MVC
This solution doesn't need web.config file changes or catch-all routes.
First, create a controller like this;
public class ErrorController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "Regular Error";
return View();
}
public ActionResult NotFound404()
{
ViewBag.Title = "Error 404 - File not Found";
return View("Index");
}
}
Then create the view under "Views/Error/Index.cshtml" as;
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<p>We're sorry, page you're looking for is, sadly, not here.</p>
Then add the following in the Global asax file as below:
protected void Application_Error(object sender, EventArgs e)
{
// Do whatever you want to do with the error
//Show the custom error page...
Server.ClearError();
var routeData = new RouteData();
routeData.Values["controller"] = "Error";
if ((Context.Server.GetLastError() is HttpException) && ((Context.Server.GetLastError() as HttpException).GetHttpCode() != 404))
{
routeData.Values["action"] = "Index";
}
else
{
// Handle 404 error and response code
Response.StatusCode = 404;
routeData.Values["action"] = "NotFound404";
}
Response.TrySkipIisCustomErrors = true; // If you are using IIS7, have this line
IController errorsController = new ErrorController();
HttpContextWrapper wrapper = new HttpContextWrapper(Context);
var rc = new System.Web.Routing.RequestContext(wrapper, routeData);
errorsController.Execute(rc);
Response.End();
}
If you still get the custom IIS error page after doing this, make sure the following sections are commented out(or empty) in the web config file:
<system.web>
<customErrors mode="Off" />
</system.web>
<system.webServer>
<httpErrors>
</httpErrors>
</system.webServer>
If you work in MVC 4, you can watch this solution, it worked for me.
Add the following Application_Error method to my Global.asax
:
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Server.ClearError();
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("action", "Index");
routeData.Values.Add("exception", exception);
if (exception.GetType() == typeof(HttpException))
{
routeData.Values.Add("statusCode", ((HttpException)exception).GetHttpCode());
}
else
{
routeData.Values.Add("statusCode", 500);
}
IController controller = new ErrorController();
controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
Response.End();
The controller itself is really simple:
public class ErrorController : Controller
{
public ActionResult Index(int statusCode, Exception exception)
{
Response.StatusCode = statusCode;
return View();
}
}
Check the full source code of Mvc4CustomErrorPage at GitHub.
I had the same problem, the thing you have to do is, instead of adding the customErrors attribute in the web.config file in your Views folder, you have to add it in the web.config file in your projects root folder
Here is true answer which allows fully customize of error page in single place. No need to modify web.config or create separate code.
Works also in MVC 5.
Add this code to controller:
if (bad) {
Response.Clear();
Response.TrySkipIisCustomErrors = true;
Response.Write(product + I(" Toodet pole"));
Response.StatusCode = (int)HttpStatusCode.NotFound;
//Response.ContentType = "text/html; charset=utf-8";
Response.End();
return null;
}
Based on http://www.eidias.com/blog/2014/7/2/mvc-custom-error-pages
I will talk about some specific cases,
if you are using 'PageNotFound method' in HomeController like below
[Route("~/404")]
public ActionResult PageNotFound()
{
return MyView();
}
it wouldn't work this. But you must clear Route tags like below,
//[Route("~/404")]
public ActionResult PageNotFound()
{
return MyView();
}
그리고 web.config에서 메소드 이름으로 변경 하면 작동합니다. 그러나 web.config에서 아래와 같은 코드를 작성하는 것을 잊지 마십시오
<customErrors mode="On">
<error statusCode="404" redirect="~/PageNotFound" />
*// it is not "~/404" because it is not accepted url in Route Tag like [Route("404")]*
</customErrors>
참고 URL : https://stackoverflow.com/questions/553922/routing-for-custom-asp-net-mvc-404-error-page
'development' 카테고리의 다른 글
tsconfig.json에서 경로를 사용하는 방법은 무엇입니까? (0) | 2020.07.22 |
---|---|
VSCode 확장을 오프라인으로 설치하는 방법은 무엇입니까? (0) | 2020.07.22 |
업로드 및 다운로드를 테스트 할 공용 FTP 서버가 있습니까? (0) | 2020.07.22 |
스프링 MVC @ PathVariable (0) | 2020.07.22 |
Intellij IDEA에서 접힌 패키지 체인을 확장하는 방법은 무엇입니까? (0) | 2020.07.22 |