简体   繁体   English

引发异常时更改HTTP状态代码

[英]Change HTTP status code when exception is thrown

I use custom class which derive from HandleErrorAttribute to handle exeptions When in my MVC application user requested content, which is not allowed to him I throw AuthenticationException and I want to change HTTP status code to 401. 我使用从HandleErrorAttribute派生的自定义类来处理异常,当在我的MVC应用程序中用户请求的内容(他不允许这样做)时,我抛出AuthenticationException,并且我想将HTTP状态代码更改为401。

public class HandleErrorFilterAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        if (typeof(AuthenticationException) == filterContext.Exception.GetType())
        {
            filterContext.HttpContext.Response.StatusCode = 401;
        }
    }
}

But my result is status code 500, when I debugging I enter in this code, in Application_Error(object, EventArgs) status is changed to 401, but finally MVC override my settings. 但是我的结果是状态代码500,当我调试该代码时,在Application_Error(object,EventArgs)中状态更改为401,但最终MVC覆盖了我的设置。
How to change response HTTP status? 如何更改响应HTTP状态? What I do wrong? 我做错了什么?

filterContext is passed by value. filterContext按值传递。 That's means that it creates copy of object that was passed as argument of function and you changed value of copy. 这意味着它将创建作为函数的参数传递的对象的副本,并且您更改了copy的值。

In common, you need to use ref keyword to pass argument by reference, so you'll have same instance of ExceptionContext as was passed; 通常,您需要使用ref关键字通过引用传递参数,因此您将拥有与传递的ExceptionContext相同的实例;

In case of override you can't change function arguments. 在覆盖的情况下,您不能更改函数参数。 So you need to rethink your program architecture. 因此,您需要重新考虑您的程序架构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM