Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ninject, WebAPI and ExceptionFilterAttribute being called twice

Good morning all,

I noticed strange behavior of Ninject (at least I think that it is the problem) in my project. The situation is the following. I use

Ninject.3.0.2-unstable-9028
Ninject.Extensions.Factory.3.0.1.0
Ninject.Web.Common.3.0.2-unstable-9012
Ninject.Web.WebApi-RC.3.0.0.22

I changed the NinjectWebCommon.cs and added code with my bindings. I have a WebApiConfig.cs which configures global exceptions handler

public static void Register(HttpConfiguration config)
{
    // Authentication token handler.
    config.MessageHandlers.Add(new TokenAuthenticationHandler());

    // Exceptions handler.
    config.Filters.Add(new ExceptionsHandler());
    ...
 }

and I have an exceptions handler class

public class ExceptionsHandler : ExceptionFilterAttribute
{
    ...
    public override void OnException(HttpActionExecutedContext context)
    {

        ...
        context.Response = context.Request.CreateErrorResponse(httpStatusCode, response);
    }
}

Now, when the request comes to the API it first gets to TokenAuthenticationHandler() object which does its magic and calls

return base.SendAsync(request, cancellationToken);

Then WebAPI controller kicks in and does its magic. In case of exception, it gets thrown and OnException of ExceptionsHandler gets called. The problem is that when OnException finishes its job, It gets called again with same context and I can't find the reason why.

I don't configure it twice. I don't have extra records in web.config. It started happening when I started using Ninject.Web.WebAPI-RC library. Before that I was using custom made Resolvers and Contexts classes that worked well, but, didn't dispose Ninject created objects. So, I decided to use what works. And everything do work except that for some reason OnException gets called twice.

If I remove

config.Filters.Add(new ExceptionsHandler());

from WebApiConfig.cs then it doesn't get called at all.

I think that Ninject has something to do with it, but I can't understand why it happens.

Thank you in advance.

like image 421
Roman K. Avatar asked Feb 18 '14 23:02

Roman K.


1 Answers

try this

 [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
 public class ExceptionsHandler : ExceptionFilterAttribute
 {
    ...
    public override void OnException(HttpActionExecutedContext context)
    {

      ...
       context.Response = context.Request.CreateErrorResponse(httpStatusCode, response);
    }
 }

This worked for me.. =)

like image 171
oCcSking Avatar answered Nov 10 '22 05:11

oCcSking