Search code examples
c#asp.net-core.net-coremiddleware

Call middleware component by condition Asp.Net Core


Is it possible to only execute middleware for requests that comes not from js. Because i have a middleware executing of which doesn't make much ssense for js requests to my server. Are there possible ways to check that request is not direct?


Solution

  • You cannot execute a middleware only for some requests, but you can check for the request to meet a condition in your middleware for exemple if an header is present in the request.

    Let's say your js client calling your api add a custom header in each request you can write a middleware checking for that header and executing some code if the header is present.

    app.Use((context, next) =>
    {
        if (context.Request.Headers.Any(h => h.Key == "Custom-Header"))
        {
               DoStuff();
        }
    
        return next();
    })