用try - catch包围的C#属性

her*_*itt 11 c# error-handling attributes

我发现自己用try {stuff} catch(异常e){log,其他东西}编写方法稍微退出,所以我试图弄清楚如何创建一个属性来帮助我.我已经非常广泛地检查了以下线程,似乎无法让我的实现工作.

属性似乎根本不起作用

ASP.NET MVC Controller.OnException未被调用

.net处理异常的属性 - 在属性访问器上使用

我的顶级web.config设置为

<customErrors mode="On" defaultRedirect="/error.html"/>
Run Code Online (Sandbox Code Playgroud)

我正在编译非调试模式.我的属性如下:

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class SafeWebMethodAttribute: ActionFilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        filterContext.ThrowIfNull();

        if (filterContext.ExceptionHandled)
        {
            return;
        }
        Log.LogException(filterContext.Exception);
        filterContext.HttpContext.Response.StatusCode = 500;
        filterContext.HttpContext.Response.Write(filterContext.Exception);
        filterContext.ExceptionHandled = true;
    }
}
Run Code Online (Sandbox Code Playgroud)

我在这里叫它 -

public class Test : Controller
{
    [SafeWebMethod]
    public ActionResult Test()
    {
        throw new ArgumentException("test");
    }
}
Run Code Online (Sandbox Code Playgroud)

我似乎无法在属性中获得断点,或者如果我更改状态代码以使其显示.

我也复制了[HandleError]属性中的代码,也无法在那里得到断点,所以我认为我的配置有问题,但我无法弄清楚是什么.

任何想法或想法将不胜感激

Mar*_*oon 3

从您提供的 .net 属性处理异常的链接开始- 在属性访问器上使用您想要的内容是不可能的(请参阅 Aaronaught 第二个代码片段中的实现)。

除非您使用某种方面框架,否则您必须实现检查属性是否存在并自行对其进行操作的代码,并在每个catch(...)语句中运行该代码。

你的想法很棒,我可能会在自己的框架中使用它,但约束仍然是你必须自己实现它。