Lucky
Lucky

Reputation: 303

.Net core controller tempdata add/remove

Implementing ExceptionFilterAttribute OnException method and need to redirect The old implementation (.Net 48) was

exceptionContext.Controller.TempData.Remove(""); 
exceptionContext.Controller.TempData.Add("");//exception message is added
exceptionContext.Controller.ControllerContext.HttpContext.Response.Redirect(url);

For the redirect I guess I can:

exceptionContext.HttpContext.Response.Redirect(url);//Is this correct?

Please suggest alternate for the remove and add?

Upvotes: 0

Views: 178

Answers (1)

Ruikai Feng
Ruikai Feng

Reputation: 11546

In .net 6,there's no exceptionContext.Controller.TempData if you want to access TempData in your ExceptionFilter,you could try to inject the TempdataDictionaryFactory into the filter

For example, I tried as below:

public class MyExceptionFilter : ExceptionFilterAttribute
    {
        private readonly ITempDataDictionaryFactory _tempDataDictionaryFactory;




        public MyExceptionFilter(ITempDataDictionaryFactory tempDataDictionaryFactory)
        {
            _tempDataDictionaryFactory = tempDataDictionaryFactory;
        }



       public override void OnException(ExceptionContext context)
        {
            var tempData = _tempDataDictionaryFactory.GetTempData(context.HttpContext);
            tempData.Add("key", "value");
            
            context.Result = new RedirectToActionResult("Error", "Home", null);
        }
    }

in Program.cs:

builder.Services.AddControllersWithViews(x=>x.Filters.Add(typeof(MyExceptionFilter)));

The Result:

enter image description here

Upvotes: 1

Related Questions