Redirect From Action Filter Attribute(从动作过滤器属性重定向)
问题描述
在 ActionFilterAttribute
中进行重定向的最佳方式是什么.我有一个名为 IsAuthenticatedAttributeFilter
的 ActionFilterAttribute
并检查了会话变量的值.如果变量为 false,我希望应用程序重定向到登录页面.我更喜欢使用路由名称 SystemLogin
进行重定向,但是此时任何重定向方法都可以.
What is the best way to do a redirect in an ActionFilterAttribute
. I have an ActionFilterAttribute
called IsAuthenticatedAttributeFilter
and that checked the value of a session variable. If the variable is false, I want the application to redirect to the login page. I would prefer to redirect using the route name SystemLogin
however any redirect method at this point would be fine.
推荐答案
设置 filterContext.Result
带有路线名称:
filterContext.Result = new RedirectToRouteResult("SystemLogin", routeValues);
你也可以这样做:
filterContext.Result = new ViewResult
{
ViewName = SharedViews.SessionLost,
ViewData = filterContext.Controller.ViewData
};
<小时>
如果你想使用RedirectToAction
:
您可以在控制器上创建一个公共 RedirectToAction
方法(最好在其基本控制器上),该方法只需从 调用受保护的
.添加此方法允许从过滤器公开调用 your RedirectToAction
>System.Web.Mvc.ControllerRedirectToAction
.
You could make a public RedirectToAction
method on your controller (preferably on its base controller) that simply calls the protected RedirectToAction
from System.Web.Mvc.Controller
. Adding this method allows for a public call to your RedirectToAction
from the filter.
public new RedirectToRouteResult RedirectToAction(string action, string controller)
{
return base.RedirectToAction(action, controller);
}
那么您的过滤器将如下所示:
Then your filter would look something like:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var controller = (SomeControllerBase) filterContext.Controller;
filterContext.Result = controller.RedirectToAction("index", "home");
}
这篇关于从动作过滤器属性重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从动作过滤器属性重定向


基础教程推荐
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01