2

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 Answers1

1

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.

Xinran Shen
  • 8,416
  • 2
  • 3
  • 12
  • 1
    My problem is solved! I thought every filter shares the same properties, turns out they don't :( Thank you so much!!! By the way I'm using other way to cast controller `var controller = (Controller)context.Controller; controller.TempData.Add("showNo", EmpNo);`, this works well too! – 亞鯉斯多德 Sep 22 '22 at 07:10
  • 1
    You're welcome, Glad to see your issue resolved. – Xinran Shen Sep 22 '22 at 07:12