I have tried to create the Exception filter
for my controller in Asp.Net Core MVC like this:
public class ControllerExceptionFilterAttribute : ExceptionFilterAttribute
{
private readonly IHostingEnvironment _hostingEnvironment;
public ControllerExceptionFilterAttribute(
IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
public override void OnException(ExceptionContext context)
{
//How construct a temp data here which I want to pass to error page?
var result = new ViewResult
{
ViewName = "Error"
};
context.ExceptionHandled = true; // mark exception as handled
context.Result = result;
}
}
I need in OnException
method work with TempData
- how can I set some exception information to TempData
in this place? I have used this TempData to some notification.
There is missing something like this: context.Controller.TempData["notification"]
- Controller property was probable removed.
You can achieve what you're looking for with the ITempDataDictionaryFactory
, which you can take into your constructor via dependency injection. This has a single function, GetTempData
, which can be used for accessing what you refer to as TempData
. Here's a complete example to suit your needs:
public class ControllerExceptionFilterAttribute : ExceptionFilterAttribute
{
private readonly IHostingEnvironment _hostingEnvironment;
private readonly ITempDataDictionaryFactory _tempDataDictionaryFactory;
public ControllerExceptionFilterAttribute(
IHostingEnvironment hostingEnvironment,
ITempDataDictionaryFactory tempDataDictionaryFactory)
{
_hostingEnvironment = hostingEnvironment;
_tempDataDictionaryFactory = tempDataDictionaryFactory;
}
public override void OnException(ExceptionContext context)
{
//How construct a temp data here which I want to pass to error page?
var tempData = _tempDataDictionaryFactory.GetTempData(context.HttpContext);
var result = new ViewResult
{
ViewName = "Error"
};
context.ExceptionHandled = true; // mark exception as handled
context.Result = result;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.