1

由于我没有为 webapi 设置 autofac,我在创建 api 控制器时出错。

但是,我似乎无法在任何地方捕捉到异常。

<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Type 'MyWeb.Web.Controllers.MyController' does not have a default constructor
</ExceptionMessage>
<ExceptionType>System.ArgumentException</ExceptionType>
<StackTrace>
at System.Linq.Expressions.Expression.New(Type type) at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
</StackTrace>
</Error>

我尝试为 Elmah 添加 WebApi contrib,然后添加了以下内容:

config.Filters.Add(new Elmah.Contrib.WebApi.ElmahHandleErrorApiAttribute());

没有让 elmah 注册异常。我在 global.asax 中添加了以下内容:

protected void Application_Error(object sender, EventArgs e)
{
    Exception exception = Server.GetLastError();
    Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
}

根本没有任何区别。

如何处理在调用控制器之前发生的错误?

4

1 回答 1

1

I wonder if this exception is just being added to the content of the HttpResponseMessage but is not actually being thrown as an exception. When implementing a dependency resolver class for use during constructor instantiation, it usually makes sense to attempt resolution, catch exceptions and return null.

For example, in non-API MVC controllers I've often used something like this:

public class UnityDependencyResolver : IDependencyResolver
{
    public readonly IUnityContainer Container;

    public UnityDependencyResolver(IUnityContainer container)
    {
        Container = container;
    }

    #region IDependencyResolver Members

    public object GetService(Type serviceType)
    {
        try
        {
            return Container.Resolve(serviceType);
        }
        catch (Exception ex)
        {
            if (ex.InnerException is TypeInitializationException)
                throw ex.InnerException;

            return null;
        }
    }
    ...
于 2013-07-26T14:41:45.687 回答