HttpHeaders too restricted; cannot call all webservices
Describe the bug I'm trying to PUT data into a REST JSON webservice from a third party. I've built a working request through Postman, which contains a Content-Type header with the value "application/json". Important: when I remove this header, the request does not work anymore.
Then I tried to rebuild this request in Business Central, but it results in the following error:
Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.
To Reproduce
WebRequest.Method('PUT');
WebRequest.GetHeaders(WebHeaders);
if WebHeaders.Contains('Content-Type') then
WebHeaders.Remove('Content-Type');
WebHeaders.Add('User-Agent','Microsoft Dynamics 365 Business Central');
WebHeaders.Add('Content-Type','application/json');
WebHeaders.Add('Authorization', GetAuthentication);
Webrequest.Content.WriteFrom(RequestContent);
//DEBUG-
WebRequest.Content.ReadAs(TempMsg);
Message(TempMsg);
//DEBUG+
WebClient.Send(WebRequest, WebResponse);
Small notes: All Http classes are called Web**, because the blue class names tickle my OCD somehow. Function GetAuthentication returns a basic auth string.
Moving the Content-Type header from the Request Header to HttpContent does make a working request, and I can see in Fiddler that the header is being sent, but the webservice does not accept this. I've also tried adding the Content-Type through the AddDefaultRequestHeader function on the HttpClient class, and using TryAddWithoutValidation instead of Add. The only way to get a 200 OK is to put the Content-Type header in the request header (using Postman).
Expected behavior I would like the error not to happen, and the request to be sent to the webservice (even though the request is not valid according to standards).
To motivate this: I don't really see the point of actually having validation on whether the header belongs in a Content-object or not. It might not comply with the standards, but why does Business Central try to enforce the rules while I can easily do this from both PHP and Postman?
In a world full of webservices programmed by all kinds of business and people, we would benefit the most from not having any validation on our request at all; even though this request is "officially illegal", inferior design, the hairy pimple of programming - you name it - it is what the software I'm trying to connect to currently requires. I'm not in the position to ask anyone to make a change at the third party, and I'm not the first developer to run into similar issue.
Versions:
- AL Language: 3.0.152816
- Business Central: Multiple (14.* and the most recent BCInsider build).
@bctails the AL API is a thin wrapper around classes in the System.Net.Http namespace in .NET https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.8 . Finding the correct place to set the headers is a fairly common problem, but it should be no different that what you would have to do in .NET. Can you give it a try using the .NET classes and let us know if you find any incompatibilities?
Hello @atoader ,
Here it is another example of HttpHeaders issue:
Content.Clear();
ContentHeader.Clear();
Content.GetHeaders(ContentHeader);
ContentHeader.Remove('Content-Type');
headerValue := CreateAuthorization(apiKey);
ContentHeader.Add('Authorization', headerValue);
RequestMsg.Content(Content);
RequestMsg.SetRequestUri(baseUrl + apiUrl);
RequestMsg.Method(method);
Client.Send(RequestMsg, ResponseMSg);
When the code reach the line with ContentHeader.Add('Authorization'..., I get the next runtime error, the value of headerValue doesn't matter:

Beside of that, commenting this line and with the method GET I get the next runtime error when executing the line Client.Send....:

Similar code in Powershell works fine:
$apiKey = 'myapikey'
$uri = New-Object System.Uri 'my.url.com'
$req = [System.Net.WebRequest]::Create($uri)
$req.Method = 'GET'
$username= $apiKey
$password= New-Guid
$usernamePassword = $username + ':' + $password
$encoding = New-Object System.Text.ASCIIEncoding
$headerValue = 'Basic ' + [System.Convert]::ToBase64String($encoding.GetBytes($usernamePassword))
$req.Headers.Add('Authorization',$headerValue);
try {
$response = $req.GetResponse()
$receiveStream = $response.GetResponseStream()
$reader = New-Object System.IO.StreamReader($receiveStream, [System.Text.Encoding]::UTF8)
Write-Output $reader.ReadToEnd()
} catch {
write-host $Error[0] -ForegroundColor Red
}
Sorry, I am using this compiler version;

And this platform version:

Regards
Hello @atoader ,
After more digging and reading other people code looks like my code is not correct, with the changes to the previous code showing in the next one, makes everything works.
var
RequestMsg: HttpRequestMessage;
RequestHeader: HttpHeaders;
RequestHeader.Clear();
RequestMsg.GetHeaders(RequestHeader);
headerValue := CreateAuthorization(apiKey);
RequestHeader.Add('Authorization', headerValue);
RequestMsg.SetRequestUri(baseUrl + apiUrl);
RequestMsg.Method(method);
Client.Send(RequestMsg, ResponseMSg);
Regards
I think we need better documentation for this API and a few scenarios. I will mark this as a documentation enhancement.
@bctails I'm curious - the Content-Type header should be added to a HttpContent as far as HttpClient is concerned, but I don't believe the way headers are transmitted is differentiated between content/request in the HTTP spec.
All headers, as far as I know, are bundled together into a set of request headers and what comes back are response headers.
The order in which the headers are added is based on the level that the header occupies, but in terms of what raw data flows across the HTTP protocol, the headers are just a list of key/values:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Messages
(scroll to the "headers" area in the above link to see an example of where the headers go)
The viability of a particular header such as Content-Type at the request/content level is a .NET thing, not an HTTP thing.
This means adding the Content-Type header at the Content should work exactly the same as adding it at the request level since it becomes the same thing when transmitted via HTTP.
.NET is just finicky about where you put it since it is supposed to make it easier to "package up" messages and separate payload settings from client settings.
One gotcha with HttpClient is that if you add content after setting the content headers, the header you added will be overwritten by a text header e.g.:
Content.GetHeaders(Headers);
Headers.Remove('Content-Type');
Headers.Add('Content-Type', 'application/json');
Content.WriteFrom('some string');
The headers transmitted in the above will be Content-Type = text/plain unfortunately.
Hello @atoader ,
After more digging and reading other people code looks like my code is not correct, with the changes to the previous code showing in the next one, makes everything works.
var RequestMsg: HttpRequestMessage; RequestHeader: HttpHeaders;RequestHeader.Clear(); RequestMsg.GetHeaders(RequestHeader); headerValue := CreateAuthorization(apiKey); RequestHeader.Add('Authorization', headerValue); RequestMsg.SetRequestUri(baseUrl + apiUrl); RequestMsg.Method(method); Client.Send(RequestMsg, ResponseMSg);Regards
@ftornero9 this is really so helpfull thanks, please provide CreateAuthorization(apiKey) method code as well.
Thanks. :)
Hello @Prareep,
Here is the code, but is only for the Web Service that I call, is not something general.
local procedure CreateAuthorization(apiKey: Text): Text
var
InStr: InStream;
OutStr: OutStream;
tmpBlob: Codeunit "Temp Blob";
b64helper: Codeunit "Base64 Convert";
begin
tmpBlob.CreateOutStream(OutStr);
OutStr.WriteText(apiKey + ':' + CreateGuid());
tmpBlob.CreateInStream(InStr);
exit('Basic ' + b64helper.ToBase64(InStr));
end;
Regards
Hello @Prareep,
Here is the code, but is only for the Web Service that I call, is not something general.
local procedure CreateAuthorization(apiKey: Text): Text var InStr: InStream; OutStr: OutStream; tmpBlob: Codeunit "Temp Blob"; b64helper: Codeunit "Base64 Convert"; begin tmpBlob.CreateOutStream(OutStr); OutStr.WriteText(apiKey + ':' + CreateGuid()); tmpBlob.CreateInStream(InStr); exit('Basic ' + b64helper.ToBase64(InStr)); end;Regards
Thank You @ftornero9 👍
Any updates on this? I get the same error message

I try to call the API from DropBox where all requests require the content-type to be set at request level.
https://www.dropbox.com/developers/documentation/http/documentation#files-list_folder
Setting the content-type as content header is not allowed for some reason.
AL Language v7.1.453917 BC Version onprem/18.0.23013.23795/de
Was facing the same problem and thanks to @charlespockert, I figured out what my problem was.
I had 2 problem in my code, the first one was as stated by @charlespockert, where the Content-Type was being changed after I was writing the body. request.Content.WriteFrom(jsonRaw);
When trying to change the Content-Type back, I was getting the "Misused header name" error with the request.GetHeaders(headers); It looks like request.GetHeaders(headers); is different from request.Content.GetHeaders(headers);
Here is my code now: `headers.clear(); request.GetHeaders(headers); headers.add('Authorization', AuthString); uri := apiVersion + apiProductVariantPutUrl; uri := uri.Replace('[variant_id]', variant_id); request.SetRequestUri(apiUrlProd + uri); request.Content.WriteFrom(jsonRaw); //this makes the Content-Type = text/plain; charset=utf-8
request.Content.GetHeaders(headers); if headers.Contains('Content-Type') then headers.Remove('Content-Type'); Headers.Add('Content-Type', 'application/json'); request.Method('PATCH'); if not client.Send(request, response) then Error('Error updating variant for Products %1 from Shopify. Web service may not be working', variant_id); if not response.IsSuccessStatusCode then Error('Web Service error \Status Code : %1 \Description : %2', response.HttpStatusCode(), response.ReasonPhrase()) else message('Variants updated!'); response.Content().ReadAs(JSonText); exit(JsonText);`
I had 2 problem in my code, the first one was as stated by @charlespockert, where the Content-Type was being changed after I was writing the body. request.Content.WriteFrom(jsonRaw);
That solved my problem! Thank you very much 👍
Hi! Thank you for this detailed report and the sustained community discussion — your feedback directly helped us understand the limitations partners were hitting with HttpHeaders.
We can confirm this was addressed internally (PR 96824) with the addition of Keys and GetValues functions using List, shipped in Business Central runtime 19.0 (2021 Wave 2). The HttpHeaders API has been significantly expanded since this was reported.
We're closing this as resolved. If you still encounter HttpHeaders limitations on a current version, please open a new issue.
Thank you for your persistence in pushing for this improvement!