In my MVC4 app I had a global.asax.cs override of Application_Error(object sender, EventArgs e)
where I could extract the exception
, statusCode
and requestedUrl
(for handling 404). That would get sent to my controller and the error page would be different for 404s vs 5xx (these get a stack trace). I don't see how to get this same info to my Error action using UseErrorHandler()
. Am I using the right approach in ASP.NET Core?
Startup.cs
using Microsoft.AspNet.Builder;
namespace NS
{
public class Startup
{
...
public virtual void Configure(IApplicationBuilder app)
{
...
app.UseExceptionHandler("/Home/Error");
...
}
}
}
HomeController.cs
using Microsoft.AspNet.Diagnostics;
using Microsoft.AspNet.Http.Features;
using Microsoft.AspNet.Mvc;
using Microsoft.Extensions.Logging;
namespace NS.Controllers
{
public class HomeController : Controller
{
static ILogger _logger;
public HomeController(ILoggerFactory factory)
{
if (_logger == null)
_logger = factory.Create("Unhandled Error");
}
public IActionResult Error()
{
var feature = HttpContext.Features.Get<IExceptionHandlerFeature>();
var error = feature?.Error;
_logger.LogError("Oops!", error);
return View("~/Views/Shared/Error.cshtml", error);
}
}
}
project.json
...
"dependencies": {
"Microsoft.AspNet.Diagnostics": "1.0.0",
...
}
...
In Beta8, agua from mars' answer is a little different.
Instead of:
var feature = Context.GetFeature<IErrorHandlerFeature>();
Use:
var feature = HttpContext.Features.Get<IExceptionHandlerFeature>();
This also requires a reference to Microsoft.AspNet.Http.Features, and the following line in Configure() in Startup.cs:
app.UseExceptionHandler("/Home/Error");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With