0

Is there a standard way to enforce mandatory request headers in .Net Core Web APIs? I want all caller apps to pass some tracking headers so that I have some traceability for call volume.

I am aware that for Swagger, it can be done via OperationFilter and custom header attribute. But for direct calls, I can think of only using custom middleware to enforce this.

Is that the right way to do it or is there other standard way to enforce it or standard libraries available for this purpose?

Kit
  • 17,129
  • 4
  • 56
  • 95
askids
  • 993
  • 1
  • 10
  • 21

1 Answers1

0

Here are a few ways to do this. There's not really a "standard" way to do it, but these ways are very common.

Outside of your project

You can enforce required headers by customizing your reverse proxy. For example, Apigee allows you to customize its rules, including enforcing headers for certain URLs. This is great because it relieves pressure and implementation on your project's endpoints. The proxy should be configured to return a 400 BAD REQUEST in those cases.

Within your project

Within the project's code, using ASP.NET middleware is how most projects take care of this. You can create a middleware that checks for the existence of the headers, and then reject the request if they are missing.

You could avoid the middleware, but then you end up bloating your controller's methods, which is usually frowned on. Either way this SO Q&A backs up the idea of returning the 400 from your code.

Kit
  • 17,129
  • 4
  • 56
  • 95