Home > Back-end >  Fail to Use Tempdata in Filter
Fail to Use Tempdata in Filter

Time:09-23

I'm using .NET 5.0, and I'm trying to pass Tempdata from my filter to _Layout.cshtml.

Here's my fitler:

using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http; //session
using Microsoft.AspNetCore.Mvc.Controllers;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System;

namespace test.Filter
{
    public class CustomAttribute : Attribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext filterContext)
        {
            //skip the unimportant parts

            string Name = context.HttpContext.Session.GetString("EmpName");
            filterContext.Controller.TempData.Add("showName", Name);
        }
    }
}

However when I'm using: filterContext.Controller.TempData.Add("Key","Value"); , I can't access Controller in my filterContext, and the error goes: 'AuthorizationFilterContext' does not contain a definition for 'Controller'.

Do I make any mistake? Or is there any using I missed?

I've found enter image description here

AuthorizationFilterContext:

enter image description here

You will find that ActionExecutingContext has a Controller property of type Object, But AuthorizationFilterContext doesn't, This is why you get the error:

AuthorizationFilterContext' does not contain a definition for 'Controller'.

You can choose to use ActionFilter and follow Kirk Larkin's solution.

  • Related