Reputation: 459
The following Exception Filter redirects exceptions to my specific error page.
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]
public class FrontofficeControllerExceptionFilterAttribute : ExceptionFilterAttribute
{
protected readonly ILogger<FrontofficeController> _logger;
protected readonly IHostingEnvironment _hostingEnvironment;
protected readonly IModelMetadataProvider _modelMetadataProvider;
public FrontofficeControllerExceptionFilterAttribute(ILogger<FrontofficeController> logger, IHostingEnvironment hostingEnvironment, IModelMetadataProvider modelMetadataProvider)
{
_logger = logger;
_hostingEnvironment = hostingEnvironment;
_modelMetadataProvider = modelMetadataProvider;
}
public override void OnException(ExceptionContext context)
{
if (context.ExceptionHandled) return;
Exception ex = context.Exception;
var result = new ViewResult { ViewName = "ApplicationError" };
context.ExceptionHandled = true; // mark exception as handled
context.Result = result;
}
}
After migrating my web app to asp.net core 1.1 the result is a blank page: the body of the response is empty and Content-Length is zero. This is the response received on the client
HTTP/1.1 200 OK
Server: Kestrel
X-SourceFiles: =?UTF-8?B?QzpcUHJvamVjdHNcaW50ZXJhaC52aXN1YWxzdHVkaW8uY29tXEludmVudGFyaW9cTWFpblxTb3VyY2VcRnJvbnRvZmZpY2Vcc3JjXEZyb250b2ZmaWNl?=
X-Powered-By: ASP.NET
Date: Wed, 30 Nov 2016 14:49:53 GMT
Content-Length: 0
have anyone experienced a similar problem and why? thankyou for any comment
Upvotes: 2
Views: 1188
Reputation: 459
the behavior is confirmed by github aspnet/mvc team. https://github.com/aspnet/Mvc/issues/5594#issuecomment-265866653
at the moment, the only solution is to render directly an HTML response. in this case marking ExceptionHandled = true works as expected.
public override void OnException(ExceptionContext context)
{
context.ExceptionHandled = true; // mark exception as handled
context.HttpContext.Response.Clear();
context.HttpContext.Response.StatusCode = 400;
context.HttpContext.Response.ContentType = new MediaTypeHeaderValue("text/html").ToString();
var home = string.Format("{0}://{1}", context.HttpContext.Request.Scheme,context.HttpContext.Request.Host);
var htmlString ="<h2>SI E' VERIFICATO UN ERRORE INATTESO</h><br/><br/>";
context.HttpContext.Response.WriteAsync(htmlString, Encoding.UTF8);
}
Upvotes: 1