Reputation: 860
I'm trying to send multiple requests as a batch through the Simple OData Client 4.0. As I need custom headers for our internal routing server side, I add them in the BeforeRequest
part of my client. This is done for the overall batch request as well, but the internal requests of the batch don't have these needed headers and it seems that there is no way on client side to add them to each internal request.
...
settings.BeforeRequest = (e) =>
{
e.Headers.Add("Authorization", "OAuth oauth_consumer_key=" + apiKey);
e.Headers.Add("V", "1");
};
...
var batch = new ODataBatch(settings);
var resultingFonts = new List<FontDto>();
// Search for the font name, to lower makes it case insensitive.
foreach (string fontName in fontNames)
batch += async c => resultingFonts.Add((await c.For<FontDto>("Fonts").Filter(" ... ").FindEntryAsync()));
batch.ExecuteAsync().Wait();
Is there any way to add my custom headers to the internal requests on client side? So that the custom headers are added to the batch request fine, but not on the internal requests.
Upvotes: 4
Views: 1525
Reputation: 2072
This question is rather old but the problem is still valid. As of today (End of 2023), Simple.OData.Client 6.0.1 does not support changing headers for inner operations inside batch requests. We can use a nasty hack to replace the Content in HttpRequestMessage
settings.BeforeRequest += delegate (HttpRequestMessage message)
{
if (message.Content is not null
&& message.RequestUri.ToString().Contains("$batch")
{
var content = message.Content as StreamContent;
if (content is not null)
{
string requestBody;
using (var reader = new StreamReader(content.ReadAsStream(), Encoding.UTF8, true))
{
reader.BaseStream.Position = 0;
requestBody = reader.ReadToEnd();
}
var replacedContent = requestBody.Replace("patternToSearch", "patternToSearch"+"additionalHeadersTxt");
var requestContent = new StringContent(replacedContent, Encoding.UTF8, MULTIPART_MIXED);
message.Content = new StreamContent(requestContent.ReadAsStream());
foreach(var header in content.Headers)
{
message.Content.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
content.Dispose();
content = null;
}
}
}
Upvotes: 1
Reputation: 870
Try adding your custom headers using the Client.UpdateRequestHeader() method.
var client = new ODataClient(settings);
client.UpdateRequestHeader(...);
var batch = new ODataBatch(client);
Upvotes: 2