Our ASP.NET Web API 2 application is consumed by mobile applications. Using Azure Application Insights we detected many responses with response code 500(Internal server error) without any Exception associated with them in Application Insights. During debugging session we did not encounter any Exception thrown.
We had a suspicion that this could be caused by client disconnects. After implementing a .net application simulating disconnects, we could replicate this issue even on a clean webapi2 project.
After further investigation we found out, that the result code 500(after the client is disconnected) occurs only when specific conditions are met. The request need to be cancelled on a non GET http operation and before ExecuteRequestHandler
asp.net event is reached. On GET requests we cannot replicate this issue, neither on requests which entered or passed the ExecuteRequestHandler
event.
Our goal is to filter out client disconnects from logs and focus on real issues.
This issue may be related to ASP.NET Web API OperationCanceledException when browser cancels the request, however the accepted solution does not work, because the disconnect occurs before any DelegatingHandler is reached. We would not use the mentioned solution, because client disconnects is not a Server issue but rather a client. For example in netcore the cancelled requests have response code 0 in logs. Anyway, the client will not see the result nor the result code because it is already gone.
Other possibly related question.
We are using the latest version Microsoft.AspNet.WebApi v5.2.7 and the investigation take place only on a development machine with IISExpress.
UPDATE
Including the minimal code to reproduce on clean webapi2 project.
Global.asax.cs
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
protected void Application_EndRequest(object sender, EventArgs e)
{
var context = HttpContext.Current;
Debug.WriteLine($"{context.Response.StatusCode}:{context.Response.SubStatusCode}:{context.Request.Path}:{context.Request.Url.AbsoluteUri}");
}
}
HomeController.cs
[RoutePrefix("api/foo")]
public class HomeController : ApiController
{
[Route("bar")]
[HttpPut]
public async Task<IHttpActionResult> Put()
{
await Task.Delay(200);
return Ok();
}
}
On average 1 of 5 cancelled requests end with 500 when cancelled after 10ms. The response code is accessible from server logs Application Insights or Output Window in VS when logged. The client will not receive the response code, because the connection is closed before any response code is returned.
UPDATE 2
Telemetry from Application Insights