I'm migrating from ASP.NET MVC 5 to ASP.NET Core and I'm having trouble with RedirectToAction
.
I'm setting the RouteValues to new { Test = "Hello World" }
.
But when it gets to my ActionFilterAttribute
, the ActionExecutingContext.RouteData.Values["Test"]
is null.
What am I missing?
Application Startup:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env,
ClarityUserManager userManager,
SignInManager<ClarityUser> signInManager)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
AppDomain.CurrentDomain.SetData("ContentRootPath", env.ContentRootPath);
AppDomain.CurrentDomain.SetData("WebRootPath", env.WebRootPath);
}
Controller:
public class SomeController : Controller
{
[HttpPost]
public ActionResult Something()
{
return RedirectToAction("Index", "Home", new { Test = "Hello World" });
}
}
ActionFilter:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class SessionExpireAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var test = filterContext?.ActionDescriptor?.RouteValues["Test"];
// test is null
var test2 = filterContext.RouteData.Values["Test"];
// test2 is also null
}
}
Home:
public class HomeController : Controller
{
public HomeController()
{
}
//
// GET: /Home/
[SessionExpire]
public ActionResult Index()
{
//
}
}
CodePudding user response:
When it gets to my ActionFilterAttribute, the ActionExecutingContext.RouteData.Values["Test"] is null. What am I missing?
First of all, you cannot get the query parameter from your filterContext?.ActionDescriptor?.RouteValues
, you have to check in httpContext
instead. Because, new { Test = "Hello World" }
would not consider as valid route rather query. If you even want to get as route value then you have to change the defination here pattern: "{controller=Home}/{action=Index}/{id?}");
and have to introduce a parameter in your Index()
action like this Index(string test)
only then you can get as RouteValues["Test"];
In addition, even you want to get the query value from your "Index", "Home"
at the first request it will always be empty because in that request our query value has not yet assign. It will only assigned when Something()
action within SomeController
will be invoked.
Way to Get Test = "Hello World"
From Action Filter:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class SessionExpireAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var actionMetadata = filterContext.HttpContext.Request.Query["Test"].GetValue();
}
}
Output: