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!
In the solution you provided, The code is in
ActionFilter, But your code is inAuthorizationFilter. Let's check the definition ofActionExecutingContextandAuthorizationFilterContextinActionFilterandAuthorizationFilter:ActionExecutingContext:
AuthorizationFilterContext:
You will find that
ActionExecutingContexthas a Controller property of type Object, ButAuthorizationFilterContextdoesn't, This is why you get the error:You can choose to use
ActionFilterand follow Kirk Larkin's solution.