Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Middleware class not called on api requests

I've created a basic webAPI project (blank web project with webAPI checked) and added the owin nuget packages to the project.

  • Microsoft.AspNet.WebApi.Owin
  • Microsoft.Owin.Host.SystemWeb
  • Owin

I've then created a Logging class, and hooked it up via startup

using AppFunc = System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>;

public class Startup
{
    public void Configuration(IAppBuilder appBuilder)
    {
        Debug.WriteLine("Startup Called");
        var config = new HttpConfiguration();
        WebApiConfig.Register(config);

        appBuilder.UseWebApi(config);

        appBuilder.Use(typeof(LoggingMiddleware));
    }
}

public class LoggingMiddleware
{
    private AppFunc Next { get; set; }

    public LoggingMiddleware(AppFunc next)
    {
        Next = next;
    }

    public async Task Invoke(IDictionary<string, object> environment)
    {
        Debug.WriteLine("Begin Request");

        await Next.Invoke(environment);

        Debug.WriteLine("End Request");
    }
}

When I run the project, and the default page opens, I see the Begin/End requests called (twice, as it happens, not sure why that is).

However, if I try to call an /api route (such as `/api/ping/'), the request completes successfully, but I do not see the Begin/End request states in the log.

What am I missing with this?

like image 397
Obsidian Phoenix Avatar asked Sep 16 '15 10:09

Obsidian Phoenix


1 Answers

Owin executes the middleware items in the order that they are registered, ending at the call to the controller (appBuilder.UseWebApi(config)) which does not appear to call next.Invoke(). Given that the code in the question has the Logging Middleware class registered after the UseWebApi call, this causes it to never be called for API requests.

Changing the code to:

public class Startup
{
    public void Configuration(IAppBuilder appBuilder)
    {
        //.....

        //This must be registered first
        appBuilder.Use(typeof(LoggingMiddleware));

        //Register this last
        appBuilder.UseWebApi(config);
    }
}

resolves the issue.

like image 166
Obsidian Phoenix Avatar answered Sep 21 '22 17:09

Obsidian Phoenix