父类中子类API的请求/响应

本文关键字:请求 响应 API 子类 父类 | 更新日期: 2023-09-27 18:07:51

我有许多继承自一个基类的类。所以我想记录请求(只是方法的输入参数)、响应(如果有的话)和任何异常(如果有的话)。

我可以修改所有的方法来实现这个,以后所有的方法都需要实现这个。

或者我在想是否有一种方法可以在基类中记录此信息,以便我可以只更新基类而不是子类方法。我不确定这样做是否可行。如果没有,最好的方法是什么?

编辑:这是一个web应用程序(MVC)和所有控制器都继承自基类,我需要记录所有的动作方法命中(请求,响应,异常等)

谢谢。

父类中子类API的请求/响应

是的,有一种方法可以做到这一点,但它可能会变得混乱。下面是一个实现:

public abstract class BaseClass
{
    public void DoSomething(int one, int two, int three)
    {
        Log(string.Format("Method: DoSomething({0}, {1}, {2})", one, two, three));
        try
        {
            DoSomethingInternal(one, two, three);
        }
        catch (Exception ex)
        {
            Log(string.Format("Method: DoSomething Exception: " + ex.ToString()));
            throw ex;
        }
    }
    public abstract void DoSomethingInternal(int one, int two, int three);
}
public class ChildClass : BaseClass
{
    public override void DoSomethingInternal(int one, int two, int three)
    {
        throw new Exception("I have no idea what to do");
    }
}

方法实际上存在于调用子类实现的抽象方法的基类中。它们可以包装在try/catch中,以捕获出现的任何错误。c# 6使异常过滤器变得更容易,但我将留给你决定使用。