I have a working Net Maui application that uses offline DataSync. I would like to add an ApiKey header to each request but the URL generated does not seem to be correct.
My code is as follows:
....
public class MyHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// Change the request-side here based on the HttpRequestMessage
request.Headers.Add("XApiKey", "abc123");
// Do the request
var response = await base.SendAsync(request, cancellationToken);
// Change the response-side here based on the HttpResponseMessage
// Return the modified response
return response;
}
}
....
var options = new DatasyncClientOptions
{
HttpPipeline = new DelegatingHandler[] { new MyHandler() },
OfflineStore = store
};
....
The response is as below:
{Method: GET, RequestUri: 'https://mybackendservice.azurewebsites.net/tables/location?$orderby=updatedAt&$count=true', Version: 1.1, Content: <null>, Headers:
{
ZUMO-API-VERSION: 3.0.0
User-Agent: Datasync/5.1.0.0 (lang=dotnet6;os=Windows/Microsoft Windows NT 10.0.22621.0;arch=X64;version=5.1.0.0)
X-ZUMO-VERSION: Datasync/5.1.0.0 (lang=dotnet6;os=Windows/Microsoft Windows NT 10.0.22621.0;arch=X64;version=5.1.0.0)
XApiKey: abc123
Accept-Encoding: gzip
}}
https://mybackendservice.azurewebsites.net/tables/location?$orderby=updatedAt&$count=true
https://mybackendservice.azurewebsites.net/tables/location?XApiKey=abc123 (<- I was expecting something like this as the request?)
404 - Not Found
Any help appreciated. Thanks Paul.
According to the code you gave, it appears that you are utilising an DeleatingHandler to include the XApiKey header in the request. The response's generated URL is the proper one for the request, but it is missing the XApiKey header you added. You must change MyHandler class to add the XApiKey header to the URL's query string. Here is an illustration of how to change the MyHandler class so that the XApiKey header is added to the query string:-
The UriBuilder's Query attribute is used to append the XApiKey header to the query string while retaining any existing query parameters.
I tried this sample code to retrieve this API in my maui app like below:-
Updated my MainPage.xaml.css with the code below:-
My MainPage.xaml with Label to retrieve the response in my home page after I click Make API Request:-
AppShell.xaml:-
Output:-