ASP.NET Core Tips
Customizing URLs
By default, apps listen on port 5000 (HTTP) or 5001 (HTTPS). We can change it with:
- command-line arguments
- the
ASPNETCORE_URLS
env launchSetings.json
- it’s not included in a publish, it’s for development only
For example:
ASPNETCORE_URLS=http://localhost:8080
- just localhost hostnameASPNETCORE_URLS=http://*:8080
- any hostname that maps to our machineASPNETCORE_URLS=http://localhost:8080;http://localhost:5000
- two ports
Reverse Proxy
When our app sits behind a reverse proxy we lose some information like:
- caller IP
- used protocol (http/https)
This information may be provided to our app by a reverse proxy via the
X-Forwarded-*
protocols. By default (using CreateDefaultBuilder
), ASP.NET
Core uses middleware that handles these headers, but that middleware is
disabled. We can enable it with env ASPNETCORE_FORWARDEDHEADERS_ENABLED = true
. This middleware overrides some of the HttpContext
properties.
Cancelling request
Every API endpoint can have CancellationToken
as one of its parameters. It’s
cancelled when client cancells request. We can use this token when handling
request. Example:
What’s the recommended way of actually handling the cancellation?
MediatR
It’s a good idea to use MediatR as a kind oif broker for requests. It makes
controller quite simple and also encourages CQRS. It requires
MediatR.Extensions.Microsoft.DependencyInjection
package to be installed in
the project where business logic is (asp.net seems to have it by default
already). Then, controllers do this:
Example of a request handler:
What’s needed is an implementation of IRequest
and IRequestHandler
.
In order to registers handler with MediatR, we need to do this in
ConfigureServices
:
It uses reflection to find all handlers. We used Details.Handler
here just to
find its assembly where all other handlers reside.
Custom error middleware
Middleware:
In Startup
:
Putting that in the beginning is a good idea.