programing

ASP.NET Web API : 설명이없는 500 내부 서버 오류

nasanasas 2020. 11. 2. 08:05
반응형

ASP.NET Web API : 설명이없는 500 내부 서버 오류


제목에서 알 수 있듯이 GET 요청에서 IQueryable 작업까지 500 개의 내부 서버 오류가 발생했습니다. 오류 본문이 비어 있습니다. 이 오류는 내 작업이 결과를 반환 한 후에 발생합니다.

ASP.NET Web API RC를 사용합니다.

해당 오류의 스택 추적을 어떻게 얻을 수 있습니까?


RC 이후,이 문제는 수정되었으며 500 내부 서버 오류와 별도로 오류 세부 정보를 받게됩니다. (이 문제는 웹 호스트 시나리오에서만 수정되었습니다.)

포맷터의 WriteToStream 메서드 중에 발생할 수있는 실제 예외의 세부 정보를 얻으려면 다음을 수행 할 수 있습니다.

ObjectContent<IEnumerable<Product>> responseContent = new ObjectContent<IEnumerable<Product>>(db.Products.Include(p => p.ProductSubcategory).AsEnumerable(), new XmlMediaTypeFormatter()); // change the formatters accordingly

            MemoryStream ms = new MemoryStream();

            // This line would cause the formatter's WriteToStream method to be invoked.
            // Any exceptions during WriteToStream would be thrown as part of this call
            responseContent.CopyToAsync(ms).Wait();

다음을 추가해 볼 수 있습니다.

GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = 
    IncludeErrorDetailPolicy.Always;

당신에 Application_Start()Global.asax에있다. 이 솔루션은 많은 일반적인 오류에 적용됩니다.

그러나 만족스러운 정보를 얻지 못한 경우 l 예외 필터를 작성하고 이를 전역 적으로 등록 하는 것을 고려해야 합니다.

이 기사 를 통해 시작하십시오. 필요한 것의 핵심은 다음과 같이 작성하고 등록하는 것입니다.

public class NotImplExceptionFilter : ExceptionFilterAttribute {
  public override void OnException(HttpActionExecutedContext context) {
     if (context.Exception is NotImplementedException) {
       context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
    }
  }
}

나는이 같은 문제에 부딪쳤다. 나는 Kiran Challa의 응답 이 내 행동 밖에서 던져지는 실제 예외를 얻는 데 도움이된다는 것을 알았다 .

내 문제를 해결하기 위해 내 컨텍스트의 ProxyCreationEnabled 속성을 false로 설정하면 한 단계 더 나아갈 수 있습니다 .

내 시나리오에서 다음 예외는 내 모델의 순환 참조 때문이었습니다. 이를 정리 한 후 팬텀 500 응답이 사라졌습니다. 아직 해결하지 못했다면 행운을 빕니다!


이것은 순환 참조와 관련이있을 수 있습니다.

http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization#handling_circular_object_references

Global.asax 파일의 Application_Start 메서드에 다음 코드를 추가해보십시오.

 var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
 json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.All;

믿을 수 없을 정도로 단순한 라우팅 취약점으로 인해이 문제가 발생했습니다. 내 Api 컨트롤러에 동일한 서명 (이름이 아님)을 가진 다른 HttpPost가있었습니다. 기본 라우팅은 이름 ​​차이를 해결하지 못했고 ServiceError 500은 Api 함수 중 하나에 도달하기 전에 제공 한 응답이었습니다. 해결 방법 : 기본 라우팅 또는 서명을 변경하고 다시 시도하십시오.

다음은 표준 WebApi2 사용에 매우 잘 작동하는 RouteConfig.cs입니다.

    public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        // Default is required in any case.
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

쿼리 매개 변수를 올바른 순서로 지정하지 않았을 때 RC에서 문제가 발생했습니다. 예를 들어를 지정 $skip=0하면 500이 표시되지만 $orderby=xxx&skip=0오류 를 지정 하지 않으면 오류가 발생합니다.


This Scenario was caused for the following reasons

  1. The problem occurred due to misformed Web.config. ( Multiple configSections)

  2. Instead of creating roslyn folder inside bin folder, I had it created at the root. (Deployment location.)

The best way to diagnose this was, to put a simple HTML page at the application location and try to browse it. 500 Error description will be displayed on this html page.

And also don't forget to add

<customErrors mode="Off"></customErrors>

to Web.config


I usually use the Global.asax to catch all error. Here is a code snip you can use

public void Application_Error(object sender, EventArgs e)
{
  Exception exc = Server.GetLastError();
  MvcApplication mvcApplication = sender as MvcApplication;
  HttpRequest request = null;
  if (mvcApplication != null) request = mvcApplication.Request;
}

I had the same problem, but the source of it was slightly different: I set the CORS policy incorrectly and that gives me 500 Internal server error, but since CORS was not working, the Access-Control-Allow-Origin header was not presented in response and browser can't read the actual response

I solved it with ChromeDevTools option Copy as cURL which allows me see the response and understand the source of error


Fredrik Normén wrote a great blog post called ASP.NET Web API Exception Handling about that topic. His solution uses custom exception classes and an exception filter attribute that can be applied to all ApiController action methods.

참고URL : https://stackoverflow.com/questions/10944938/asp-net-web-api-non-descriptive-500-internal-server-error

반응형