programing

redirectMode="ResponseRewrite"를 설정할 때 사용자 지정 오류가 작동하지 않음

starjava 2023. 6. 11. 10:13
반응형

redirectMode="ResponseRewrite"를 설정할 때 사용자 지정 오류가 작동하지 않음

에서는 커스텀 를 사용자 정의 오류를 .redirectMode="ResponseRewrite" SP1의 기능3.5 SP1 버전):

<customErrors mode="RemoteOnly" defaultRedirect="Error.aspx" redirectMode="ResponseRewrite">
    <error statusCode="404" redirect="404.aspx" />
</customErrors> 

인 오류 때 페이지)를입니다.customErrors만약 내가 그것을 제거한다면.redirectMode="ResponseRewrite"부분적으로, 그것은 잘 작동합니다.

동일한 서버에서 호스트되는 다른 사이트에서 동일한 설정을 사용하므로 서버에 3.5 SP1이 설치되어 있습니다.

아이디어 있어요?

MVC 애플리케이션에서 이 작업을 수행하려는 모든 사용자에게 중요한 사항은ResponseRewrite사용하다Server.Transfer막에서로후 , ,,defaultRedirect파일 시스템의 정규 파일에 해당해야 합니다. 보하니아,Server.Transfer경로와 의 오류 페이지가 제공되는 경우 MVC 않므지으로오류, 컨경는우되제작공의해,Server.Transfer파일 시스템에서 찾을 수 없는 /Error/Whating을 찾고 일반 404 오류 페이지를 반환합니다!

나에게 완벽하게 작동한 유일한 방법은 사용자 지정 오류를 끄고 web.config를 통해 iis의 오류 페이지를 바꾸는 것입니다.응답과 함께 올바른 상태 코드를 전송하며, mvc를 거치지 않는 장점이 있습니다.

여기 코드가 있습니다.

  1. 사용자 지정 오류 끄기

    <customErrors mode="Off" />
    
  2. 오류 페이지 바꾸기

    <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>
    

고참을 합니다. 사용responsemode="file"URL이 파일에 대한 직접 링크인 경우

정보 : http://tipila.com/tips/use-custom-error-pages-aspnet-mvc

IIS는 오류 상태 코드를 보고 사용자의 오류 페이지 대신 자체 오류 페이지를 표시합니다.이 문제를 해결하려면 오류 페이지의 코드 뒤 페이지에서 이를 설정하여 IIS가 이 작업을 수행하지 못하도록 해야 합니다.

Response.TrySkipIisCustomErrors = true;

이 기능은 IIS 7 이상에서만 작동하며, 이전 버전의 IIS에서는 오류 페이지 설정을 사용하여 재생해야 합니다.

의때문에존한에 에.Server.Transfer내부적으로 실행되는 것으로 보입니다.ResponseRewriteMVC와 호환되지 않습니다.

이것은 저에게 눈에 띄는 기능의 구멍처럼 느껴져서, 저는 HTTP 모듈을 사용하여 이 기능을 다시 구현하기로 결정했습니다. 그래서 이것이 작동하도록 말입니다.아래 솔루션을 사용하면 일반적인 경우와 마찬가지로 유효한 MVC 경로(실제 파일 포함)로 리디렉션하여 오류를 처리할 수 있습니다.

<customErrors mode="RemoteOnly" redirectMode="ResponseRewrite">
    <error statusCode="404" redirect="404.aspx" />
    <error statusCode="500" redirect="~/MVCErrorPage" />
</customErrors>

이는 다음 플랫폼에서 테스트되었습니다.

  • 통합 파이프라인 모드의 MVC4(IIS Express 8)
  • 클래식 모드의 MVC4(VS 개발 서버, Cassini)
  • 클래식 모드의 MVC4(IIS6)

namespace Foo.Bar.Modules {

    /// <summary>
    /// Enables support for CustomErrors ResponseRewrite mode in MVC.
    /// </summary>
    public class ErrorHandler : IHttpModule {

        private HttpContext HttpContext { get { return HttpContext.Current; } }
        private CustomErrorsSection CustomErrors { get; set; }

        public void Init(HttpApplication application) {
            System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");
            CustomErrors = (CustomErrorsSection)configuration.GetSection("system.web/customErrors");

            application.EndRequest += Application_EndRequest;
        }

        protected void Application_EndRequest(object sender, EventArgs e) {

            // only handle rewrite mode, ignore redirect configuration (if it ain't broke don't re-implement it)
            if (CustomErrors.RedirectMode == CustomErrorsRedirectMode.ResponseRewrite && HttpContext.IsCustomErrorEnabled) {

                int statusCode = HttpContext.Response.StatusCode;

                // if this request has thrown an exception then find the real status code
                Exception exception = HttpContext.Error;
                if (exception != null) {
                    // set default error status code for application exceptions
                    statusCode = (int)HttpStatusCode.InternalServerError;
                }

                HttpException httpException = exception as HttpException;
                if (httpException != null) {
                    statusCode = httpException.GetHttpCode();
                }

                if ((HttpStatusCode)statusCode != HttpStatusCode.OK) {

                    Dictionary<int, string> errorPaths = new Dictionary<int, string>();

                    foreach (CustomError error in CustomErrors.Errors) {
                        errorPaths.Add(error.StatusCode, error.Redirect);
                    }

                    // find a custom error path for this status code
                    if (errorPaths.Keys.Contains(statusCode)) {
                        string url = errorPaths[statusCode];

                        // avoid circular redirects
                        if (!HttpContext.Request.Url.AbsolutePath.Equals(VirtualPathUtility.ToAbsolute(url))) {

                            HttpContext.Response.Clear();
                            HttpContext.Response.TrySkipIisCustomErrors = true;

                            HttpContext.Server.ClearError();

                            // do the redirect here
                            if (HttpRuntime.UsingIntegratedPipeline) {
                                HttpContext.Server.TransferRequest(url, true);
                            }
                            else {
                                HttpContext.RewritePath(url, false);

                                IHttpHandler httpHandler = new MvcHttpHandler();
                                httpHandler.ProcessRequest(HttpContext);
                            }

                            // return the original status code to the client
                            // (this won't work in integrated pipleline mode)
                            HttpContext.Response.StatusCode = statusCode;

                        }
                    }

                }

            }

        }

        public void Dispose() {

        }


    }

}

사용.

웹.config에 최종 HTTP 모듈로 포함합니다.

  <system.web>
    <httpModules>
      <add name="ErrorHandler" type="Foo.Bar.Modules.ErrorHandler" />
    </httpModules>
  </system.web>

  <!-- IIS7+ -->
  <system.webServer>
    <modules>
      <add name="ErrorHandler" type="Foo.Bar.Modules.ErrorHandler" />
    </modules>
  </system.webServer>

이 질문이 좀 오래된 질문인 것은 알지만, 이 질문이 작동하기 위해 정적 파일일 필요는 없다는 점을 지적해야 한다고 생각했습니다.

저도 비슷한 일을 당했는데, 당신의 Error.aspx에서 그 오류를 찾는 것이 문제입니다. 우리의 경우 사용 중인 마스터 페이지가 세션 데이터에 의존하고 있고 ResponseRewrite가 설정되었을 때 세션을 Error.aspx 페이지에서 사용할 수 없기 때문입니다.

세션을 사용할 수 없는 이유가 당사의 특정 앱 구성 때문인지, 아니면 ASP.net 의 "설계상" 부분 때문인지는 아직 파악하지 못했습니다.

문제가 Error.aspx에 있다는 것을 알게 되었습니다.여전히 문제의 원인이 되는 error.aspx의 실제 오류를 찾을 수 없습니다.

정적 html 파일로 페이지를 변경하여 문제를 해결했습니다.

ASP.NET MVC 컨트롤러로 쿼리를 전송하는 오류 페이지를 aspx에 작성했습니다.이 asx 페이지에 쿼리를 다시 작성하면 사용자 지정 컨트롤러로 쿼리가 전송됩니다.

protected void Page_Load(object sender, EventArgs e)
{
  //Get status code
  var queryStatusCode = Request.QueryString.Get("code");
  int statusCode;
  if (!int.TryParse(queryStatusCode, out statusCode))
  {
    var lastError = Server.GetLastError();
    HttpException ex = lastError as HttpException;
    statusCode = ex == null ? 500 : ex.GetHttpCode();
  }
  Response.StatusCode = statusCode;

  // Execute a route
  RouteData routeData = new RouteData();
  string controllerName = Request.QueryString.Get("controller") ?? "Errors";
  routeData.Values.Add("controller", controllerName);
  routeData.Values.Add("action", Request.QueryString.Get("action") ?? "Index");

  var requestContext = new RequestContext(new HttpContextWrapper(Context), routeData);
  IController controller = ControllerBuilder.Current.GetControllerFactory().CreateController(requestContext, controllerName);
  controller.Execute(requestContext);
}

자세한 내용은 여기에서 확인하십시오. https://stackoverflow.com/a/27354140/143503

@Amila의 게시물과 그 게시물의 확인 및 완료에 따르면, 저는 같은 문제를 가지고 있으며, 구글을 많이 파지만 정답을 찾을 기회가 없었습니다.문제는 당신이 작업할 때입니다.ASP.Net Web Application그것이 무엇이든MVC그렇지 않으면 이전 방법을 사용하여 사용자 지정 오류를 달성할 수 없습니다.Webform project.
사용 중인 경우 여기에 옵션을 선택합니다.ASP.Net Web Application(그것이 그것이든 아니든.MVC또는 아님):

내 시나리오에서는 특정 404 오류에 대한 사용자 지정 오류를 정의하려고 합니다. 다른 오류는 404 오류와 동일하게 정의되었습니다.


세나리오1:사용자 정의 페이지는 단순합니다.HTML파일을 보관하고 에 배치합니다.root:

<configuration>
   <system.web>
      <customErrors mode="Off" />
   </system.web>
   <system.webServer>
       <httpErrors errorMode="Custom" existingResponse="Replace">
           <remove statusCode="404" subStatusCode="-1" />
           <error statusCode="404" path="ErrorPage.html" responseMode="File" />
       </httpErrors>
   </system.webServer>
</configuration>



세나리오2: Your custom page is an aspx page and placed in the root:

<configuration>
   <system.web>
      <customErrors mode="Off" />
   </system.web>
   <system.webServer>
       <httpErrors errorMode="Custom" existingResponse="Replace">
           <remove statusCode="404" subStatusCode="-1" />
           <error statusCode="404" path="ErrorPage" responseMode="Redirect" />
       </httpErrors>
   </system.webServer>
</configuration>

참고: 다음과 같은 이유로 aspx 확장을 제거합니다.RouteConfig.csASP.net application사용할 수 있습니다.ErrorPage.aspx원한다면, 선택 사항입니다.


세나리오3: Your custom page is an aspx page and placed in the [ex: Page folder in The root (~/Page/ErrorPage.aspx)]:
The tip here that I noticed is 사용해서는 안 됩니다.~/ to the root addressing; So I just addresing without ~/ mark:

<configuration>
   <system.web>
      <customErrors mode="Off" />
   </system.web>
   <system.webServer>
       <httpErrors errorMode="Custom" existingResponse="Replace">
           <remove statusCode="404" subStatusCode="-1" />
           <error statusCode="404" path="Page/ErrorPage" responseMode="Redirect" />
       </httpErrors>
   </system.webServer>
</configuration>

저의 경우, 제 오류 페이지에는 세션을 사용하려는 사용자 컨트롤이 있는 마스터 페이지가 있었습니다.세션을 사용할 수 없는 경우 HttpException: "enableSessionState가 true로 설정된 경우에만 구성 파일 또는 페이지 지시사항에서 세션 상태를 사용할 수 있습니다."가장 쉬운 해결책은 정적 html로 전환하는 것이고, 두 번째로 쉬운 해결책은 더 간단한 오류 페이지를 사용하는 것이며, 가장 어려운 해결책은 오류 페이지가 어디에서도 예외를 발생시키지 않고 오류가 발생하지 않도록 하는 것입니다.

redirectMode="ResponseRewrite"를 사용하는 경우 web.config 파일의 rewrite 영역에 무언가를 추가해야 한다는 것을 알게 되었습니다.문제는 당신의 사이트가 고장 났을 때입니다!사이트에서 다시 쓰기를 처리하는 "virtual.aspx"를 호출할 수 없기 때문에 URL을 다시 쓸 수 없습니다!

언급URL : https://stackoverflow.com/questions/781861/customerrors-does-not-work-when-setting-redirectmode-responserewrite

반응형