Stefan Watt
Stefan Watt

Reputation: 57

ASP.NET Core API Controllers - How to debug properly

Over the past couple weeks I've been working with an ASP.NET Core Backend(Remote Ubuntu Machine, SSH only, Kestrel).

When sending an HTTP-Request to the Server oftentimes it won't be handled the way I expected it to.

Examples:

Is there a way to see the headers, body, etc. of the request that arrived at the Server?

How is the body data processed before the corresponding action method is called?


I've been reading the Console Output and setting breakpoints to figure out whats going on.

Which is fine if there's an Exception thrown or theres something going wrong inside the action method.

But it doesn't help me understand what's happening before the action method is executed.

Upvotes: 1

Views: 4508

Answers (1)

crgolden
crgolden

Reputation: 4614

You can add a middleware in the pipeline to inspect any requests. In the middleware, you will have access to the HttpContext and all its properties (i.e. the request and its headers). As long as you place your app.Use() call before your app.UseMvc() call, you will have access to the request before it enters an action.

More info on middleare is here: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware

Once it enters an action, you have access to the Request object in the controller as well. So you can inspect anything on the request (i.e. headers) however you prefer (locals window, watch window, etc.).

All the properties you can access if you inherit from ControllerBase are here: https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.controllerbase

As Polyfun mentioned, the best approach would be to add robust logging.

Upvotes: 2

Related Questions