In my PowerShell script I am trying to insert a request header in my ODataServices client request. I am using Register-ObjectEvent to do that. This is a technique that works fine in .NET but for some reason does not in PowerShell I am suspecting that PS provides different access to the $EventArgs
$proxy = New-ODataServiceProxy "http://localhost.:50055/Service/"
$addAuthenticationHeader =
{
$EventArgs.RequestHeaders.Add("X-Authorization", "Y2xhcmsua2VudEBzdXBlci5jb206c3VwZXJtYW46bWFpbg==")
}
Register-ObjectEvent -InputObject $proxy -EventName "SendingRequest" -Action $addAuthenticationHeader
$topic = New-Object -TypeName "MyServer.Entities.Topic"
$topic.Name = "hola from PS"
$topic.About = "about"
$proxy.AddObject("Topics", $topic)
$proxy.SaveChanges()
When the request goes out on SaveData it does not have the added header in it. Any suggestions?
I ran into the same problem with the properties I modified on $EventArgs seemingly having no effect. I'm not real clear on the details, but when you use the -Action parameter of Register-ObjectEvent it creates a PSEventJob to run your event handler/ScriptBlock. Since $addAuthenticationHeader is being run within a Job, I suspect the EventArgs object that gets passed to it is not the same one that the event was raised with, so the source object never sees the changes you make.
As a workaround, I used the Add-Type cmdlet to define a C# class to do the event handling instead. I'm not familiar with the API you're using, but it'd look something like this:
Add-Type -TypeDefinition @"
using System;
using ProxyNamespace;
namespace StackOverflow
{
public static class ProxyHelper
{
public static void RegisterSendingRequest(ProxyType proxy)
{
proxy.SendingRequest += Proxy_SendingRequest;
}
private static void Proxy_SendingRequest(object sender, ProxyEventArgs e)
{
e.RequestHeaders.Add(
"X-Authorization",
"Y2xhcmsua2VudEBzdXBlci5jb206c3VwZXJtYW46bWFpbg=="
);
}
}
}
"@ -ReferencedAssemblies $ProxyAssemblyPath;
You'll need to replace ProxyNamespace, ProxyType, ProxyEventArgs, and $ProxyAssemblyPath with appropriate values, then just replace this...
$addAuthenticationHeader =
{
$EventArgs.RequestHeaders.Add("X-Authorization", "Y2xhcmsua2VudEBzdXBlci5jb206c3VwZXJtYW46bWFpbg==")
}
Register-ObjectEvent -InputObject $proxy -EventName "SendingRequest" -Action $addAuthenticationHeader
...with this...
[StackOverflow.ProxyHelper]::RegisterSendingRequest($proxy);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With