HTTP 헤더가 IIS7.5로 전송 된 후 서버가 상태를 설정할 수 없습니다.
프로덕션 환경에서 가끔 예외가 발생합니다.
- 공정 정보
- 프로세스 ID : 3832
- 프로세스 이름 : w3wp.exe
- 계정 이름 : NT AUTHORITY \ NETWORK SERVICE
- 예외 정보
- 예외 유형 : System.Web.HttpException
- 예외 메시지 : HTTP 헤더를 보낸 후 서버에서 상태를 설정할 수 없습니다.
- 정보를 요청하다
- 요청 URL : http://www.myulr.pl/logon
- 요청 경로 : / logon
- 사용자 호스트 주소 : 10.11.9.1
- 사용자 : user001
- 인증 됨 : True
- 인증 유형 : 양식
- 스레드 계정 이름 : NT AUTHORITY \ NETWORK SERVICE
- 스레드 정보
- 스레드 ID : 10
- 스레드 계정 이름 : NT AUTHORITY \ NETWORK SERVICE
- 명의 도용 : False
Stack trace: at System.Web.HttpResponse.set_StatusCode(Int32 value) at
System.Web.HttpResponseWrapper.set_StatusCode(Int32 value) at
System.Web.Mvc.HandleErrorAttribute.OnException(ExceptionContext filterContext) at
System.Web.Mvc.ControllerActionInvoker.InvokeExceptionFilters(ControllerContext controllerContext, IList(1) filters, Exception exception) at
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) at System.Web.Mvc.Controller.ExecuteCore() at
System.Web.Mvc.MvcHandler.<>c__DisplayClass8.<BeginProcessRequest>b__4() at
System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.<MakeVoidDelegate>b__0() at
System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8(1).<BeginSynchronous>b__7(IAsyncResult _) at
System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult(1).End() at
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) at
System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& ompletedSynchronously)
테스트 환경에서이 오류를 발견하지 못했습니다. 무엇을 확인해야합니까?
ASP.NET MVC 2 (Release Candidate 2)를 사용하고 있습니다.
나는 원인에 대해 Vagrant와 광범위하게 동의합니다.
- 작업이 실행 중이며 응답 스트림에 마크 업을 작성했습니다.
- 스트림이 버퍼링되지 않아 마크 업 쓰기가 시작되기 전에 응답 헤더가 기록됩니다.
- 보기에 런타임 오류가 발생했습니다.
- 예외 처리기가 상태 코드를 200이 아닌 다른 것으로 설정하려고 시도합니다.
- 헤더가 이미 전송 되었기 때문에 실패합니다.
Vagrant에 동의하지 않는 부분은 "바인딩에 오류가 없습니다"해결책입니다. View 바인딩에서 런타임 오류가 발생할 수 있습니다 (예 : null 참조 예외).
이에 대한 더 나은 해결책은 Response.BufferOutput = true;
모든 바이트가 응답 스트림으로 전송되기 전에 확인하는 것 입니다. 예를 들어 컨트롤러 작업 또는 응용 프로그램의 On_Begin_Request에서. 이를 통해 서버 전송, 쿠키 / 헤더 등을 자연스럽게 종료 응답 또는 호출 종료 / 플러시까지 바로 설정할 수 있습니다.
물론 버퍼가 스택에서 더 아래로 플러시되거나 false로 설정되지 않았는지 확인하십시오.
MSDN 참조 : HttpResponse.BufferOutput
위의 응답에 추가하십시오. ASP.Net MVC를 처음 사용하기 시작했을 때 이와 동일한 문제가 있었고 컨트롤러 작업 중에 Response.Redirect를 수행했습니다.
Response.Redirect("/blah", true);
Response.Redirect
액션 을 반환하는 대신 다음을 반환 해야했습니다 RedirectAction
.
return Redirect("/blah");
HTTP 서버는 오류를 지정하거나 데이터 전송을 시작할 때까지 응답 헤더를 클라이언트로 다시 보내지 않습니다. 데이터를 클라이언트로 다시 보내기 시작하면 서버는 먼저 응답 헤드 (상태 코드 포함)를 보내야합니다. 헤더가 전송되면 더 이상 헤더에 상태 코드를 넣을 수 없습니다.
여기에 일반적인 문제가 있습니다. 페이지를 시작하고 몇 가지 초기 태그 (예 :)를 보냅니다 <head>
. 그런 다음 서버는 먼저 SUCCESS 상태로 가정 된 HTTP 응답 헤더를 보낸 후 해당 태그를 클라이언트에 보냅니다. 이제 페이지의 핵심 작업을 시작하고 문제를 발견합니다. 오류 상태를 포함 할 응답 헤더가 이미 전송 되었기 때문에이 시점에서 오류를 보낼 수 없습니다.
해결책은 다음과 같습니다. 콘텐츠를 생성하기 전에 오류가 있는지 확인하십시오. 그래야만 문제가 없다고 확신 할 때 태그와 같은 콘텐츠를 보낼 수 있습니다.
귀하의 경우 양식에서 POST 요청을 처리하는 로그인 페이지가있는 것 같습니다. 초기 HTML을 버리고 사용자 이름과 암호가 유효한지 확인하십시오. 당신이 생성되기 전에 대신, 먼저 사용자 / 암호를 인증해야 어떤 모두에서 HTML을.
내가 설정과 같은 문제를 가지고 StatusCode
다음과 Response.End
에서 HandleUnauthorizedRequest
의 방법AuthorizeAttribute
var ctx = filterContext.HttpContext;
ctx.Response.StatusCode = (int)HttpStatusCode.Forbidden;
ctx.Response.End();
.NET 4.5 이상을 사용하는 경우 앞에이 줄을 추가하십시오. Response.StatusCode
filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;
.NET 4.0을 사용하는 경우 SuppressFormsAuthenticationRedirectModule을 사용해보십시오 .
리디렉션을 수행하기 전에 이것을 확인하는 것은 어떻습니까?
if (!Response.IsRequestBeingRedirected)
{
//do the redirect
}
You are actually trying to redirect a page which has some response to throw. So first you keep the information you have throw in a buffer using response.buffer = true
in beginning of the page and then flush it when required using response.flush
this error will get fixed
I remember the part from this exception : "Cannot modify header information - headers already sent by" occurring in PHP. It occurred when the headers were already sent in the redirection phase and any other output was generated e.g.:
echo "hello"; header("Location:http://stackoverflow.com");
Pardon me and do correct me if I am wrong but I am still learning MS Technologies and I was trying to help.
I apologize, but I'm adding my 2 cents to the thread just in case anyone has the same problem.
- I used Forms Authentication in my MVC app
- But some controller-actions were "anonymous" i.e. allowed to non-authenticated users
- Sometimes in those actions I would still want users to be redirected to the login form under some condition
- to do that - I have this in my action method:
return new HttpStatusCodeResult(401)
- and ASP.NET is super nice to detect this, and it redirects the user to the login page! Magic, right? It even has the properReturnUrl
parameter etc.
But you see where I'm getting here? I return 401. And ASP.NET redirects the user. Which is essentially returns 302. One status code is replaced with another.
And some IIS servers (just some!) throw this exception. Some don't. - I don't have it on my test serevr, only on my production server (ain't it always the case right o_O)
I know my answer is essentially repeating what's already said here, but sometimes it's just hard to figure out where this overwriting happens exactly.
We were getting the same error - so this may be useful to some.
For us the cause was super simple. An interface change confused an end user and they were pressing the back button in the browser at a 'bad' time after a form submission (sure we should probably have used a PRG pattern, but we didn't).
We fixed the issue and the user is no longer pressing the back button. Problem solved.
İf someone still having this problem.Try to use instead of ovverriding
public void OnActionExecuting(ActionExecutingContext context)
{
try
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
if (!HttpContext.Current.Response.IsRequestBeingRedirected)
{
context.Result = new RedirectToRouteResult(
new RouteValueDictionary { { "controller", "Login" }, { "action", "Index" } });
}
}
}
catch (Exception ex)
{
new RouteValueDictionary { { "controller", "Login" }, { "action", "Index" } });
}
}
'developer tip' 카테고리의 다른 글
두 개의 CPU가있는 VirtualBox로 Vagrant에서 VM을 어떻게 만들 수 있습니까? (0) | 2020.11.05 |
---|---|
Google 애드워즈 전환 onclick을 추적하는 방법은 무엇입니까? (0) | 2020.11.04 |
UpdatePanel의 버튼에서 전체 포스트 백을 강제로 적용하려면 어떻게합니까? (0) | 2020.11.04 |
Zsh는 명령 앞에 _가있는 명령을 자동 수정하려고합니다. (0) | 2020.11.04 |
JavaScript 객체가 JSON인지 확인하는 방법 (0) | 2020.11.04 |