简体   繁体   English

c#WebAPI中的ExceptionHandler

[英]ExceptionHandler in c# WebAPI

I have a question regarding how exactly this thing works. 我有一个关于这个东西究竟是如何工作的问题。

public class GlobalExceptionHandler: ExceptionHandler
{
    private string _pvtMsg;

    public override void handle(ExceptionHandlerContext context)
    {
        //few if else conditions
        if()
        {
        }
        else if
        {
            _pvtMsg = "some value";
        }
        context.Result="Some random value depending upon if else execution";
    }
}

Now when _pvtMsg is set after that, whenever exception occurs it always have that same value as before. 现在,在_pvtMsg之后设置_pvtMsg时,每当发生异常时,它总是具有与之前相同的值。

Does, when I set _pvtMsg = "a"; 当我设置_pvtMsg = "a"; in the else if condition, the next time an error occurs _pvtMsg still have value "a" ? else if条件下,下次发生错误时_pvtMsg仍然有值"a"

Is there only a single instance of handler available throughout the lifespan of my application and hence this is happening? 在我的应用handler整个生命周期中是否只有一个handler实例可用,因此会发生这种情况? Or are there any other reasons? 还是有其他原因吗? Any documents for reference would be appreciated. 任何参考文件将不胜感激。

Btw: this handler is registered with the Register method of the WebApiConfig . 顺便说一句:这个处理程序是使用WebApiConfigRegister方法Register的。

config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler()); 

Your assumption is correct. 你的假设是正确的。 Since you register an Instance of GlobalExceptionHandler (with the new keyword) _pvrMsg will always have the value of the previous (successful) call. 由于您注册了GlobalExceptionHandler实例 (使用new关键字), _pvrMsg将始终具有上一个(成功)调用的值。

If _pvrMsg is critical for whatever you are planning on doing in your if block, I'd recommend locking this part of the code to make sure handle doesn't execute multiple times at once. 如果_pvrMsg对于你在if块中计划进行的操作至关重要,我建议锁定这部分代码以确保handle不会一次执行多次。

The easiest way to do this would be: 最简单的方法是:

public class GlobalExceptionHandler: ExceptionHandler
{
    private string _pvtMsg;
    private readonly object _lock = new object();

    public override void handle(ExceptionHandlerContext context)
    {
        lock(_lock)
        {
            //few if else conditions
            if()
            {
            }
            else if
            {
                _pvtMsg = "some value";
            }
            context.Result="Some random value depending upon if else execution";
        }
    }
}

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

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