About today’s newsletter :
Recap of Refit
How to add query attributes
How to set content type header
How to add bearer token header for all calls
Recap of Refit
Refit is the automatic type-safe REST library for .NET Core, Xamarin and .NET.
It lets you define your API calls using C# interfaces in simple three steps.
That is not the target for today’s newsletter, if you are not aware about how to use Refit in .NET then check this article I wrote earlier :
👉 What Are Query Attributes and How to Add Them?
When you pass parameters in the query string of a URL, the parameters are appended to the URL after a question mark (?), and each parameter is specified as a key-value pair. Multiple parameters are separated by an ampersand (&). The general syntax is as follows:
http://example.com/path/to/resource?parameter1=value1
We can achieve similar in refit like this :
Parameter with [Query] would be passed as a query string and the one in command would be passed in body.
If you wish to add multiple parameters then add them and just add [Query] before that.
👉 How to Properly Set the Content Type Header
Content headers are essential, we need to set them with each request. Let me show you how would I add that.
I prefer to make a delegating handler for it, here you can read about it :
That is how I would add default header :
👉 How to Add Bearer Token in Headers
Similarly I can create a delegating handler for adding bearer token.
We can register it similarly as we did with content header. Add this handler only with your secure APIs which need token for successful call.
Whenever you’re ready, there are 2 ways I can help you
Promote yourself to 8200+ subscribers by Sponsoring my Newsletter
Get a FREE eBook from Gumroad that contains 30 .NET Tips (2900+ downloads)
Completely new to refit and relatively new to asp.net. I'm puzzled where to put that service registration:
1) In the same method as the API call?
2) Somewhere like program.cs?
Anyway, where does the variable 'services' come from?