2

我不熟悉 ASP.NET Core 操作的自定义过滤器属性。如果使用自定义方法过滤器不存在某些数据,我需要重定向到另一个操作。

这是我的尝试:

[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行显示为错误(带有红色下划线),因为它是 void 方法,而不是操作结果。正如我提到的,我不熟悉自定义过滤器。

请问有什么帮助吗?

4

1 回答 1

1

是的。只需将实例的Result属性设置为您的. 它应该如下所示:ActionExecutingContextRedirectToActionResult

 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);
 }
于 2022-01-10T00:03:46.810 回答