【问题标题】:How can I make an action filter cause a filtered action to return HttpNotFoundResult?如何使操作过滤器导致过滤的操作返回 HttpNotFoundResult?
【发布时间】:2014-12-12 04:38:21
【问题描述】:

我有一个自定义操作过滤器,用于非常明确的内容长度限制。它的工作方式如下:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    if (filterContext.HttpContext.Request.ContentLength >= MaxLength)
    {
        throw new HttpException("MaxLengthFilter: Request has Content-Length > " + MaxLength);
    }
    base.OnActionExecuting(filterContext);
}

如果对超过最大值的内容长度调用的任何操作返回更有意义的结果,例如 HTTP 404.13,我会更愿意。如果我直接在操作内部进行过滤,我可以使用'return new HttpNotFoundResult()',但过滤器的OnActionExecuting 方法是void 类型。

这更加复杂,因为一些需要过滤的操作是ActionResult,而一些是JsonResult,而后者需要对HttpNotFoundResult进行序列化。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4 http httpresponse action-filter


    【解决方案1】:

    没有必要抛出异常。您可以重定向到自定义错误操作。 这是一个像这样的question

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.Request.ContentLength >= MaxLength)
        {
           filterContext.Result = RedirectToAction("Error401_13", "Error"); //for example
           return;
        }
        base.OnActionExecuting(filterContext);
    }
    

    【讨论】:

    • 我猜Error401_13 会在哪里做一个简单的return new HttpNotFoundResult?确实是朝着正确方向迈出的一步。我不知何故从未想过我可以在过滤器中返回一个重定向。
    • 再想一想,Server.Transfer 可能比重定向更好。这是一个模糊的 ajax 世界,我想避免浏览器往返。
    • Error401_13 可以根据您的目的返回结果。如果需要错误页面,则返回动作,如果需要返回错误代码,则抛出异常,如果需要一些json响应则返回Json(new {yourResponce});
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多