7

Whatever happened to the Cancel property on the ActionExecutingContext? How would one abort a RenderAction when using an ActionFilterAttribute or is there another way to skin this cat?

  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
   if(!filterContext.HttpContext.User.Identity.IsAuthenticated)
   {
    return;
   }
   base.OnActionExecuting(filterContext);
  }

The code above continues to execute the Action it has been applied to despite exiting the OnActionExecuting operation?

--- Further To original post: Thanks for the answers below, however, I don't think I have made the context clear enough, I am trying to invalidate the following call:

<% Html.RenderAction("Menu", "Shared", new { id = Model.OtherUserId }); %>

When a user is not authenticated this action should return nothing, I could easily put an 'if' block on the view, however, I would like to keep the rule in the controller.

4

3 回答 3

14

这很好用 Mattias 结果是这样的:

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            filterContext.Result = new EmptyResult();
            return;
        }
        base.OnActionExecuting(filterContext);
    }
于 2010-01-26T16:31:26.740 回答
3

不,您不能从动作过滤器中取消渲染。您不应该这样做的原因有很多。客户会看到什么?错误页面?没有?

我猜您正在构建一个授权操作过滤器,如果您未登录,它将呈现其他内容。如果您未登录,框架中已经有一个(AuthorizeAttribute)将您重定向到登录页面。他们这样做的方式它在框架中是更改正在执行的结果(filterContext.Result = [[new result]];)。如果您不喜欢它的工作方式,您可以构建自己的实现。

如果您仍然需要取消渲染或类似的事情,您将需要构建自己的 ActionResult 并在 Execute 方法中执行您需要的任何逻辑。

- 更新 -

如果你想使用渲染动作,你应该把逻辑放在控制器中,如果你没有登录则返回空结果(框架中有一个名为“EmptyResult”的动作结果)。这种逻辑属于控制器动作。

于 2010-01-26T12:13:07.353 回答
0

Mattias 和 rjarmstrong 已经回答了问题。这是过滤器和控制器的完整代码:

public class CancelFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        //before execution
        var id = filterContext.RequestContext.HttpContext.Request.Params["id"];
        if (id == "0")
        {
            filterContext.Result = new EmptyResult();
            return;
        }
        base.OnActionExecuting(filterContext);
    }

    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        //after execution
    }
}


[CancelFilter]
public class HomeController : Controller
{
    public ActionResult DoSome(string id)
    {
        return View();
    }

    ...
}
于 2016-03-17T12:47:52.793 回答