Fail to Use Tempdata in Filter

512 views Asked by At

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 a similar question, but the solution just didn't work for me. (Same problem, filterContext.Controller not found)

Any help would be greatly appreciated!

1

There are 1 answers

2
Xinran Shen On BEST ANSWER

In the solution you provided, The code is in ActionFilter, But your code is in AuthorizationFilter. Let's check the definition of ActionExecutingContext and AuthorizationFilterContext in ActionFilter and AuthorizationFilter:

ActionExecutingContext:

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.