Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine which middleware answered on ASP.NET Core websites

Is there a way to determine (on way back) which middleware answered the request? Is there a stacktrace somewhere or something similar?

What I seek could be a stacktrace up to the last middleware called, accessible in the httpcontext object.

I could add some fake middlewares just setting flags, but I would prefer to have something that does not need adding code.

It would be for example to differenciate requests that have been served by static files and those served by MVC (this is an example, but not exhaustive, I have several middlewares serving response, and I would like to be able to identify which one).

like image 935
Jean Avatar asked Nov 07 '22 18:11

Jean


1 Answers

ASP.NET Core Logging API already provide what you need. You can obtain the following output :

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/api/todo/0

info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1] Executing action method TodoApi.Controllers.TodoController.GetById (TodoApi) with arguments (0) - ModelState is Valid

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1] Request starting HTTP/1.1 GET https://localhost:44301/css/bootstrap.css

info: Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware[2] Sending file. Request path: '/css/bootstrap.css'. Physical path: XXX

The simpliest way of achieving this would be to create an appsettings.Development.json file where you can set the following configuration :

{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    },
    "Console":
    {
      "IncludeScopes": true
    }
  }
}

By default, you will be able to see the logs in the console. You could change where the logs are displayed by using differents ILoggerProvider.

I recommend you to read the Logging chapter on MSDN

like image 186
spidyx Avatar answered Nov 14 '22 22:11

spidyx