在 ASP.NET MVC 控制器结果中设置 HTTP 状态不会呈现视图

发布于 2024-09-08 12:05:53 字数 287 浏览 3 评论 0原文

我有一个自定义的 ActionResult 用于返回某些 HTTP 错误,例如 NotFoundResult 和 ForbiddenResult,它们都派生自 ViewResult。

我将它们用于诸如在操作过程中未在数据库中找到实体时使用 404 进行短路操作的情况。

在这些结果对象中,我将 HTTP 状态设置为适当的数字。当我这样做时,这些 ViewResults 引用的视图不会呈现。我必须将状态保留为 200 OK 才能渲染我的视图。

如何在 ASP.NET MVC 2.0 中设置适当的状态并呈现视图?

I have a custom ActionResult for returning certain HTTP Errors, like NotFoundResult and ForbiddenResult, they all derive from ViewResult.

I use them for instances like short circuiting actions with a 404 if an entity was not found in the database during the course of an action.

Within these result objects, I set the HTTP Status to the appropriate number. When I do that, the view that these ViewResults reference does not render. I have to leave the status as 200 OK in order for my view to be rendered.

How do I set an appropriate status AND render a view in ASP.NET MVC 2.0?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

作妖 2024-09-15 12:05:53

我有一个自定义的 ActionResult
返回某些 HTTP 错误,例如
NotFoundResult 和 ForbiddenResult,
它们都派生自 ViewResult。

请允许我向您建议另一种错误处理方法:

首先创建错误控制器和相应的视图:

public class ErrorController : Controller
{
    public ActionResult General()
    {
        return View();
    }

    public ActionResult HttpError404()
    {
        return View();
    }

    public ActionResult HttpError500()
    {
        return View();
    }
}

在 Global.asax 中定义 Application_Error 方法:

protected void Application_Error(object sender, EventArgs e)
{
    var exception = Server.GetLastError();
    // TODO: Log the exception with your favorite logging framework

    Response.Clear();
    var httpException = exception as HttpException;

    var routeData = new RouteData();
    // Take the ErrorController
    routeData.Values.Add("controller", "error");

    if (httpException == null)
    {
        // Use the General action for any unhandled error
        routeData.Values.Add("action", "general");
    }
    else
    {
        switch (httpException.GetHttpCode())
        {
            case 404:
                routeData.Values.Add("action", "httpError404");
                break;
            case 500:
                routeData.Values.Add("action", "httpError500");
                break;
            default:
                routeData.Values.Add("action", "general");
                break;
        }
    }

    // Add the exception to route data so that the error controller 
    // could use it with RouteData.Values["error"]
    routeData.Values.Add("error", exception);

    Server.ClearError();
    IController errorController = new ErrorController();
    errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}

最后抛出适当的异常:

public class HomeController: Controller
{
    public ActionResult Index(int id)
    {
        var model = _repository.GetModel(id);
        if (model == null)
        {
            throw new HttpException(404, "Model not found with id = " + id);
        }
        return View(model);
    }
}

I have a custom ActionResult for
returning certain HTTP Errors, like
NotFoundResult and ForbiddenResult,
they all derive from ViewResult.

Allow me to suggest you an alternative error handling:

Start by creating an error controller and the corresponding views:

public class ErrorController : Controller
{
    public ActionResult General()
    {
        return View();
    }

    public ActionResult HttpError404()
    {
        return View();
    }

    public ActionResult HttpError500()
    {
        return View();
    }
}

In Global.asax define the Application_Error method:

protected void Application_Error(object sender, EventArgs e)
{
    var exception = Server.GetLastError();
    // TODO: Log the exception with your favorite logging framework

    Response.Clear();
    var httpException = exception as HttpException;

    var routeData = new RouteData();
    // Take the ErrorController
    routeData.Values.Add("controller", "error");

    if (httpException == null)
    {
        // Use the General action for any unhandled error
        routeData.Values.Add("action", "general");
    }
    else
    {
        switch (httpException.GetHttpCode())
        {
            case 404:
                routeData.Values.Add("action", "httpError404");
                break;
            case 500:
                routeData.Values.Add("action", "httpError500");
                break;
            default:
                routeData.Values.Add("action", "general");
                break;
        }
    }

    // Add the exception to route data so that the error controller 
    // could use it with RouteData.Values["error"]
    routeData.Values.Add("error", exception);

    Server.ClearError();
    IController errorController = new ErrorController();
    errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}

Finally throw appropriate exceptions:

public class HomeController: Controller
{
    public ActionResult Index(int id)
    {
        var model = _repository.GetModel(id);
        if (model == null)
        {
            throw new HttpException(404, "Model not found with id = " + id);
        }
        return View(model);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文