gpt4 book ai didi

c# - 当API Controller 创建失败时,在MVC4中处理异常吗?

转载 作者:行者123 更新时间:2023-12-03 07:54:57 26 4
gpt4 key购买 nike

由于没有为webapi设置autofac ,因此在创建api Controller 时出现错误。

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

<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注册异常(exception)。
我在global.asax中添加了以下内容:
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
}

完全没有任何区别。

如何处理在调用 Controller 之前发生的错误?

最佳答案

我想知道是否将此异常仅添加到HttpResponseMessage的内容中,但实际上没有作为异常抛出。当实现在构造函数实例化过程中使用的依赖解析器类时,尝试解析,捕获异常并返回null通常很有意义。

例如,在非API MVC Controller 中,我经常使用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;
}
}
...

关于c# - 当API Controller 创建失败时,在MVC4中处理异常吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17881287/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com