.Net Core 3.1
I have an ExceptionFilter, where I'd like to pass TempData value with a RedirectResult.
Here is my Code below:
public class CustomExceptionFilterAttribute : IExceptionFilter
{
private readonly ITempDataProvider _tempDataProvider;
public CustomExceptionFilterAttribute(ITempDataProvider tempDataProvider)
{
_tempDataProvider = tempDataProvider;
}
public void OnException(ExceptionContext context)
{
//Log The Exception here
//After Log
var url = context.HttpContext.Request.Path.ToUriComponent();
context.ExceptionHandled = true;
context.HttpContext.Response.Clear();
var tempData = new TempDataDictionary(context.HttpContext, _tempDataProvider);
tempData.Add("UserFriendlyMessage", "An Error Occured! Please contact Admin!");
tempData.Keep("UserFriendlyMessage"); //This didn't work either...
var result = new RedirectResult(url);
context.Result = result;
}
}
[TypeFilter(typeof(CustomExceptionFilterAttribute))]
public class MyController : Controller
{...
public IActionResult MyAction()
{
return View();
}
[HttpPost]
public IActionResult MyAction(MyModel model)
{
try
{
int a = 5;
int b = a / 0;
}
catch(Exception ex)
{
}
return View();
}
So as you see above, my aim is to Redirect the user to the same page(where exception occurs) and prevent them to redirect a 500StatusCode Error Page.
Actually this code redirects user the way I want to, but just TempData value is not passing.
I have tried:
- context.HttpContext.Response.Clear(); Tried this code and without this code.
- tempData.Keep("UserFriendlyMessage"); Tried this code and without this code.