是否可以使用自定义操作过滤器重定向到另一个操作?
Is it possible to redirect to another action using a custom action filter?
我不熟悉 ASP.NET 核心操作的自定义过滤器属性。
我需要重定向到另一个操作,以防某些数据不存在使用自定义方法过滤器。
这是我的尝试:
[AttributeUsage(AttributeTargets.Class| AttributeTargets.Method, AllowMultiple = false)]
public class IsCompanyExistAttribute: ActionFilterAttribute
{
private readonly ApplicationDbContext context;
public IsCompanyExistAttribute(ApplicationDbContext context)
{
this.context = context;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//base.OnActionExecuting(filterContext);
if (context.Companies == null)
{
return RedirectToAction(actionName: "Msg", controllerName: "Account",
new { message = "You are not allowed to register, since the company data not exist !!!" });
}
}
我没有使用 filterContext
。 RedirectToAction
行显示为错误(带有红色下划线),当然,因为它是无效方法,而不是操作结果。正如我提到的,我不熟悉自定义过滤器。
有什么帮助吗?
是的,是的。只需设置 Result
property of the ActionExecutingContext
instance to your RedirectToActionResult
。它应该类似于以下内容:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var controller = filterContext.Controller as ControllerBase;
if (context.Companies == null && controller != null)
{
filterContext.Result = controller.RedirectToAction(
actionName: "Msg",
controllerName: "Account",
new { message = "You are not allowed to register, since the company data not exist !!!" }
);
}
base.OnActionExecuting(filterContext);
}
我不熟悉 ASP.NET 核心操作的自定义过滤器属性。 我需要重定向到另一个操作,以防某些数据不存在使用自定义方法过滤器。
这是我的尝试:
[AttributeUsage(AttributeTargets.Class| AttributeTargets.Method, AllowMultiple = false)]
public class IsCompanyExistAttribute: ActionFilterAttribute
{
private readonly ApplicationDbContext context;
public IsCompanyExistAttribute(ApplicationDbContext context)
{
this.context = context;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//base.OnActionExecuting(filterContext);
if (context.Companies == null)
{
return RedirectToAction(actionName: "Msg", controllerName: "Account",
new { message = "You are not allowed to register, since the company data not exist !!!" });
}
}
我没有使用 filterContext
。 RedirectToAction
行显示为错误(带有红色下划线),当然,因为它是无效方法,而不是操作结果。正如我提到的,我不熟悉自定义过滤器。
有什么帮助吗?
是的,是的。只需设置 Result
property of the ActionExecutingContext
instance to your RedirectToActionResult
。它应该类似于以下内容:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var controller = filterContext.Controller as ControllerBase;
if (context.Companies == null && controller != null)
{
filterContext.Result = controller.RedirectToAction(
actionName: "Msg",
controllerName: "Account",
new { message = "You are not allowed to register, since the company data not exist !!!" }
);
}
base.OnActionExecuting(filterContext);
}